prealloc
prealloc copied to clipboard
False positives when appends are conditional
Even with simple=true, the linter reports about preallocating slices. Here is one such example:
var ents []*Entity // <--- ***false positive here***
if !m.fromMe() {
e := entityWithID(m.normalizedCallerID)
ents = append(ents, &e) // <-- conditional append only
}
for _, p := range m.participants {
pID := p.normalizedID()
if pID == senderID {
continue
}
e := p.entity()
ents = append(ents, &e) // <-- also conditional due to continue
}
As you can see, there is no way to know how many elements will be added to the slice - could be 0 or more, with no way to tell beforehand.
Loops that use continue, or appends which are conditional, should be omitted from this linter.
Suggestion for a fix: Simply ignore loops that contain a continue statement. Avoiding false positives feels more important than having a few false negatives. ChatGPT can prototype the code to identify continue statements in the loop body's AST if needed.
Hi @kevgo, I unfortunately don't have the bandwidth to work on this issue, but that seems like a reasonable heuristic to me.