Skip to content

needless_range_loop disregards multiple indexed variables #3032

Open
@gnzlbg

Description

@gnzlbg

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thing

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions