prealloc icon indicating copy to clipboard operation
prealloc copied to clipboard

line of sight loops trick prealloc

Open carnott-snap opened this issue 6 years ago • 1 comments

When ranging over a list that contains conditional break/continue directives and a slice = append(slice, element) at the end, prealloc suggests preallocation.

No lint triggered

var a []int
for i := range []struct{}{{}, {}, {}} {
        if i < 1 {
                a = append(a, i)
        } 
}

Lint triggered

var a []int
for i := range []struct{}{{}, {}, {}} {
        if i < 1 {
              continue
        } 
        a = append(a, i)
}

carnott-snap avatar Aug 07 '19 00:08 carnott-snap

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)
}
// ...

luisdavim avatar Oct 02 '21 22:10 luisdavim