A loop tests one variable and steps another
What it finds
for j := 0; j < n; i++: a loop that declares and tests one variable but steps another never changes the one it tests. This is the typical slip in nested loops, where the step of the outer loop was copied.
The init statement must declare exactly the variable that the condition tests, the condition must not mention the stepped variable, as in for lo := 0; lo < hi; hi--, nor call anything but len and cap, as iterators do in for it := m.Iter(); it.Next(); n++, and the body must not change the declared variable.
From the rule's source, wrong_loop_variable.rs.
package p func f(grid [][]int, it interface{ Next() bool }, ch chan []int) { for i := 0; i < len(grid); i++ { for j := 0; j < len(grid); i++ {tx0 reports: the loop tests j, but i++ steps another variable grid[i][j] = 0 } for j := 0; j < len(grid[i]); j++ { } for j := 0; j < len(grid[i]); i++ { } } n := 0 for ok := true; ok; n++ {tx0 reports: the loop tests ok } for ok := true; ok; n++ { ok = n < 10 } for ok := true; ok; n++ { set(&ok) } for x := it; x.Next(); n++ { } for j := 0; j < n; n-- { } for j := 0; j < len(<-ch); n++ { }} func set(p *bool) { *p = false } Turn it on, off or suppress it
The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:
[rules]
"tx0/go:wrong-loop-variable" = "off"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:wrong-loop-variable] reason="..."tx0 explain tx0/go:wrong-loop-variable shows the same in the terminal. Found a false positive? Report it.