Single Iteration Loop
ID |
go.single_iteration_loop |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Go |
Tags |
reliability, suspicious |
Description
Reports a loop whose body always terminates on the first iteration — the last statement of
the loop body is an unconditional return or break that is a direct child of the loop. The
loop therefore runs at most once and the loop construct is pointless.
Rationale
A loop that always exits on the first turn is almost always a bug: the jump was meant to be
conditional, or the loop should be a single statement. The check is conservative — only an
unconditional return/break as the loop body’s last direct statement is flagged. A jump
guarded by an if does not always fire and is legitimate, and continue restarts the loop
rather than leaving it, so neither is reported.
for _, v := range items {
return v // FLAW — the loop returns on the first element
}
for _, v := range items {
if v > 0 {
return v // OK — the return is conditional
}
}
Remediation
If only the first element is wanted, drop the loop and index directly. If the jump should
depend on a condition, guard it with an if.