← All lints

reverse_index

L0528Idiomswarn

Hand-written reversed copy

[xs[xs.len - 1 - i] for i in 0..xs.len]: the copy is xs.reversed()

Flagged
let xs = [3, 1, 4]
print([xs[xs.len - 1 - i] for i in 0..xs.len])
Write instead
let xs = [3, 1, 4]
print(xs.reversed())

Why

[xs[xs.len - 1 - i] for i in 0..xs.len] spells out the reversal index by index; the - 1 and the bound must both be right. xs.reversed() says it in one word, costs the same O(n)O(n) and allocates the same new list. The fix applies when the copy runs over the whole list (0..xs.len), xs is a plain name or field, and the checker types it as a List; a Str is left alone because s.reversed() is a Str, not a list of characters. To walk backwards without a copy, use xs.rev.

The practice it serves

A hand-written pattern the language or the standard library already says in one step. Family: H. C++ habits.

Not flagged

A near miss: close to the pattern, but not it.

Near miss
let xs = [3, 1, 4]
let s: Str = read()
print([xs[xs.len - 1 - i] for i in 0..xs.len - 1])
print([xs[xs.len - 2 - i] for i in 0..xs.len - 1])
print([s[s.len - 1 - i] for i in 0..s.len])

Turn it off

For one block, wrap it in with lint(reverse_index: allow):. For a project, add reverse_index = "allow" under [lints] in cp.toml.

Generated from spec/lints/reverse_index, the same record the linter is built from.