rust-lang / rust-lang/rust-clippy
needless_range_loop makes questionable suggestion
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
Pretty simple. Here is the code (I didn't write it):
pub fn sum(&self) -> (Vec<f64>, Vec<f64>) {
let mut sum_x = vec![0.0; self.x[0].len()];
let mut sum_y = vec![0.0; self.y[0].len()];
for i in 0..self.x.len() {
for j in 0..self.x[i].len() {
sum_x[j] += self.x[i][j];
}
}
for i in 0..self.y.len() {
for j in 0..self.y[i].len() {
sum_y[j] += self.y[i][j];
}
}
(sum_x, sum_y)
}
self.x and self.y are Vec<Vec<f64>>.
Clippy says:
warning: the loop variable `j` is used to index `sum_x`
--> gai-rs\vendor\NeuroFlow\src\data\mod.rs:194:22
|
194 | for j in 0..self.x[i].len() {
| ^^^^^^^^^^^^^^^^^^
|
= note: `#[warn(clippy::needless_range_loop)]` on by default
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_range_loop
help: consider using an iterator
|
194 | for (j, <item>) in sum_x.iter_mut().enumerate().take(self.x[i].len()) {
| ~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
warning: the loop variable `j` is used to index `sum_y`
--> gai-rs\vendor\NeuroFlow\src\data\mod.rs:200:22
|
200 | for j in 0..self.y[i].len() {
| ^^^^^^^^^^^^^^^^^^
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_range_loop
help: consider using an iterator
|
200 | for (j, <item>) in sum_y.iter_mut().enumerate().take(self.y[i].len()) {
| ~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I get the suggestion, but is it really better in this case? Is it a zero-cost abstraction?
Regardless of whether it compiles to the same code (I doubt it does, but I haven't checked), it's definitely harder to reason about.
Is there a better suggestion clippy could make for summing up all the items in a Vec<Vec<_>>?
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the needless_range_loop lint and the example in gai-rs\vendor\NeuroFlow\src\data\mod.rs around lines 194 and 200. Compare the current iterator suggestion with the nested Vec<Vec> summation shown in the issue, then determine what revised suggestion would be clearer and preserve the intended behavior.】【。
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100