-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Open
Labels
C-bugCategory: Clippy is not doing the correct thingCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't haveIssue: The lint was triggered on code it shouldn't have
Description
Summary
The following code triggers needless_range_loop but it suggests code changes that do not work in this case.
Lint Name
needless_range_loop
Reproducer
I tried this code, which creates a symmetric nxn matrix:
pub fn create_distance_matrix(n: usize, distance: fn(usize, usize) -> f64) -> Vec<Vec<f64>> {
let mut matrix: Vec<Vec<f64>> = vec![vec![0_f64; n]; n];
for i in 0..n {
for j in i+1..n {
let cost = distance(i, j);
matrix[i][j] = cost;
matrix[j][i] = cost;
}
}
matrix
}I saw this happen:
warning: the loop variable `i` is used to index `matrix`
--> src/tsp.rs:172:14
|
172 | for i in 0..n {
| ^^^^
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.92.0/index.html#needless_range_loop
help: consider using an iterator and enumerate()
|
172 - for i in 0..n {
172 + for (i, <item>) in matrix.iter_mut().enumerate().take(n) {
|
warning: the loop variable `j` is used to index `matrix`
--> src/tsp.rs:173:18
|
173 | for j in i+1..n {
| ^^^^^^
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.92.0/index.html#needless_range_loop
help: consider using an iterator and enumerate()
|
173 - for j in i+1..n {
173 + for (j, <item>) in matrix.iter_mut().enumerate().take(n).skip(i+1) {
The lint suggests to work with iter_mut().enumerate(). If I try to do that, I run into borrow checker problems as the inner loop assigns values to 2 cells in different rows.
I expected to see this happen:
Rewriting the code without range loop does not seem to be straight forward. The lint should not suggest an approach that does not work.
Version
cargo 1.92.0 (344c4567c 2025-10-21)
release: 1.92.0
commit-hash: 344c4567c634a25837e3c3476aac08af84cf9203
commit-date: 2025-10-21
host: x86_64-unknown-linux-gnu
Additional Labels
No response
Metadata
Metadata
Assignees
Labels
C-bugCategory: Clippy is not doing the correct thingCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't haveIssue: The lint was triggered on code it shouldn't have