Skip to content

A problem with needless_range_loop #2072

Closed
@leonardo-m

Description

@leonardo-m

For code like:

fn main() {
    let mut v = [0; 10];
    for i in 0 .. v.len() {
        v[i] += i;
    }
}

Currently Clippy gives notes like:

warning: the loop variable `i` is used to index `v`
 --> .../main.rs:3:5
  |
3 | /     for i in 0 .. v.len() {
4 | |         v[i] += i;
5 | |     }
  | |_____^
  |
  = note: #[warn(needless_range_loop)] on by default
  = help: for further information visit https://rust-lang-nursery.github.io/rust-clippy/v0.0.161/index.html#needless_range_loop
help: consider using an iterator
  |
3 |     for (i, <item>) in v.iter().enumerate() {
  |  

Replacing array-indexing Rust code with iterators sometimes helps the compiler remove some array bound tests (but in this case the compiler is able to remove then), but in general this code change increases the compilation time (and often the max amount of memory the compiler uses). This isn't a problem if the programmer replaces few loops-with-indexing with loops-with-iterators, but introducing hundreds or thousands of loops-with-iterators in a large Rust program could slow down the compilation a lot. So in my opinion Clippy needless_range_loop should be more careful and conservative in suggesting this kind of code change.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions