Skip to content

needless_range_loop intrusiveness #6075

@leonardo-m

Description

@leonardo-m

This is a case where needless_range_loop probably gives a good suggestion:

fn main() {
    let v = [10, 20, 30];
    for i in 0 .. v.len() {
        println!("{} {}", i, v[i]);
    }
}

Clippy says:

warning: the loop variable `i` is used to index `v`
 --> src/main.rs:3:14
  |
3 |     for i in 0 .. v.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
  |
3 |     for (i, <item>) in v.iter().enumerate() {
  |         ^^^^^^^^^^^    ^^^^^^^^^^^^^^^^^^^^

warning: 1 warning emitted

But in many many cases similar suggestions are not so good. I suspect that replacing a hundred regular range for loops with iter/iter_mut + enumerates increases the work (the time) the compiler (the back-end) has to do to optimize the code. And in many cases (most cases in my codebase) this suggestion messes up the signficant amount of imperative code inside the loop. So while in general I think such lint is useful to have in Clippy, for me it's one of the most annoying Clippy lints. So I suggest to reduce the number of situations where it fires. and move the rest of situations into a pedentic bin that's disabled by default.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't haveS-needs-discussionStatus: Needs further discussion before merging or work can be started

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions