A counting or conditional loop always leaves at the end of its first iteration
What it finds
for i := 0; i < n; i++ { ...; return x }: the body ends in a return, break or panic on every path through it, and nothing in it continues the loop, so the loop runs at most once. Usually the exit belonged inside an if, or after the loop.
The loop must have a condition or a post statement, and its body must end in a return, an unlabeled break or a call of the builtin panic, with no continue and no goto anywhere in the body, and the body must have at least one statement before the exit: for scanner.Scan() { break } waits for one line on purpose. Loops over range are left alone, since taking the first element of a map or channel that way is common.
From the rule's source, loop_runs_once.rs.
package p func first(xs []int, n int) int { for i := 0; i < n; i++ { if xs[i] > 0 { xs[i]-- } return xs[i]tx0 reports: the loop always leaves here, so it runs at most once } for i := 0; i < n; i++ { if xs[i] < 0 { continue } return i } for k := range xs { return k } for { return 0 }} Turn it on, off or suppress it
The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/go:loop-runs-once" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/go:loop-runs-once] reason="..."tx0 explain tx0/go:loop-runs-once shows the same in the terminal. Found a false positive? Report it.