Index loop that only reads xs[i]
for i in 0..xs.len that only reads xs[i]
let xs: List<Int> = [1, 2, 3]
for i in 0..xs.len:
print(xs[i])let xs: List<Int> = [1, 2, 3]
for x in xs:
print(x)Why
Iterating for i in 0..xs.len solely to read xs[i] introduces an unnecessary index variable. Iterate directly with for x in xs:.
The practice it serves
A hand-written pattern the language or the standard library already says in one step. Family: S.seq: building.
Not flagged
A near miss: close to the pattern, but not it.
let xs: List<Int> = [1, 2, 3]
for i in 0..xs.len:
print(i, xs[i])Turn it off
For one block, wrap it in with lint(index_only_loop: allow):. For a project, add index_only_loop = "allow" under [lints] in cp.toml.
Generated from spec/lints/index_only_loop, the same record the linter is built from.