Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve Consider preallocating (prealloc) lint?

Tags:

slice

lint

go

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?

like image 381
Mahmoud Masih Tehrani Avatar asked Jan 14 '20 13:01

Mahmoud Masih Tehrani


1 Answers

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()
}
like image 87
icza Avatar answered Sep 23 '22 22:09

icza