rust-lang / rust-lang/rust-clippy

needless_range_loop disregards multiple indexed variables

Open
#3,032 1 comment 5 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the needless_range_loop lint and reproduce the linked Playground example to understand how multiple indexed variables are handled. Done means the lint accounts for all indexed variables and provides an appropriate zip-based recommendation for this case.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.