prealloc icon indicating copy to clipboard operation
prealloc copied to clipboard

False positives when appends are conditional

Open mholt opened this issue 1 year ago • 2 comments
trafficstars

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.

mholt avatar Aug 29 '24 16:08 mholt

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.

kevgo avatar Jan 09 '25 02:01 kevgo

Hi @kevgo, I unfortunately don't have the bandwidth to work on this issue, but that seems like a reasonable heuristic to me.

alexkohler avatar Jan 09 '25 17:01 alexkohler