Search code examples
goslicelint

How to resolve Consider preallocating (prealloc) lint?


I catch Consider preallocating [to] (prealloc) this problen in golangci-lint my code is:

var to []string
for _, t := range s.To {
    to = append(to, t.String())
}

Do you have an idea to resolve this problem in lint?


Solution

  • Preallocate a slice with capacity so append() will have less (or no) copying to do:

    to := make([]string, 0, len(s.To))
    for _, t := range s.To {
        to = append(to, t.String())
    }
    

    Or even better, don't use append() but assign to individual slice elements:

    to := make([]string, len(s.To))
    for i, t := range s.To {
        to[i] = t.String()
    }