Open
Description
Summary
Given that i
is a Range
iterator (and the likes), if both vec1[i]
and vec2[1][i]
exist, clippy would say that i
is used to index vec1
only, and suggest a loop over vec1
instead of a Range
.
Lint Name
needless_range_loop
Reproducer
I tried this code:
const COUNT: usize = 10;
fn main() {
let a = vec![vec![0u8; COUNT]; COUNT]; // Must be 2+ dimensions!
#[allow(clippy::useless_vec)] // irrelevant.
let b = vec![0u8; COUNT];
for i in 0..COUNT {
let _ = a[1][i]; // Doing `a[i]` doesn't send the warning.
let _ = b[i];
}
}
I saw this happen:
the loop variable `i` is used to index `b`
for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_range_loop
`#[warn(clippy::needless_range_loop)]` on by defaultclippy[needless_range_loop](rust-analyzer-diagnostics-view:/diagnostic%20message%20[0]?0#file:///home/Ryo/dev/rust/mcli/src/commands/clock/mod.rs)
mod.rs(164, 13): consider using an iterator and enumerate(): `(i, <item>)`, `b.iter().enumerate().take(COUNT)`
I expected to see this happen:
No warning. In my specific case, it was a match
statement with 2 arms, one indexing a
and another indexing b
, so I only needed one of the arrays - the example isn't made like that to make it as simple as possible.
Version
rustc 1.87.0 (17067e9ac 2025-05-09)
binary: rustc
commit-hash: 17067e9ac6d7ecb70e50f92c1944e545188d2359
commit-date: 2025-05-09
host: x86_64-unknown-linux-gnu
release: 1.87.0
LLVM version: 20.1.1
Additional Labels
@rustbot label +L-style