prealloc
prealloc copied to clipboard
line of sight loops trick prealloc
When ranging over a list that contains conditional break/continue directives and a slice = append(slice, element) at the end, prealloc suggests preallocation.
var a []int
for i := range []struct{}{{}, {}, {}} {
if i < 1 {
a = append(a, i)
}
}
var a []int
for i := range []struct{}{{}, {}, {}} {
if i < 1 {
continue
}
a = append(a, i)
}
I also get a false positive with code that looks like this:
// ...
var (
a []string
u map[string]struct{}
)
// some code to populate u
// where a is used to return in case of errors
a = make([]string,0, len(u))
for s := range u {
a = append(s)
}
// ...