Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

needless_range_loop disregards multiple indexed variables #3032

Open
gnzlbg opened this issue Aug 11, 2018 · 1 comment
Open

needless_range_loop disregards multiple indexed variables #3032

gnzlbg opened this issue Aug 11, 2018 · 1 comment
Labels
C-bug Category: Clippy is not doing the correct thing

Comments

@gnzlbg
Copy link
Contributor

gnzlbg commented Aug 11, 2018

Playground:

pub struct Foo {
    x: [f32; 3]
}

pub fn foo(x: &mut Foo, p: &mut [f32]) {
    for i in 0..3 {
        x.x[i] += p[i];
    }
}

produces

warning: the loop variable `i` is used to index `p`
 --> src/main.rs:6:14
  |
6 |     for i in 0..3 {
  |              ^^^^
  |
  = note: #[warn(needless_range_loop)] on by default
  = help: for further information visit https://rust-lang-nursery.github.io/rust-clippy/v0.0.212/index.html#needless_range_loop
help: consider using an iterator
  |
6 |     for (i, <item>) in p.iter().enumerate().take(3) {
  |         ^^^^^^^^^^^    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

which suggests that only p is indexed, or at least disregards that x.x is also indexed. In this case, zip would probably be a much better recommendation than using any kind of index.

Using the index to index all of the variables but one feels a bit weird:

pub fn foo(x: &mut Foo, p: &mut [f32]) {
    for (i, p) in p.iter().enumerate().take(3) {
        x.x[i] += p;
    }
}

Also, in this case, a zip would not require the take(3) because the length would be fixed as part of the zip.

@ISSOtm
Copy link

ISSOtm commented Apr 26, 2021

Not exactly the same, but I had a similar false positive that I believe is related.

for i in 0..tab.len() {
    if let Some(pal) = &tab[i] {
        // SNIP
        tab[i] = None;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C-bug Category: Clippy is not doing the correct thing
Projects
None yet
Development

No branches or pull requests

3 participants