Skip to content

FP explicit_counter_loop: var incremented before usage #6074

Closed
@matthiaskrgr

Description

@matthiaskrgr

I tried this code:

pub fn main() {
    let mut i = 0;
    let v = vec!["a", "b", "c"];
    for x in &v {
        i += 1;
        println!("{}", i)
    }
}

explicit_counter_loop will trigger here and suggest to use .iter().enumerate().
The problem is that we increment BEFORE using (and not at the end of the loop) so the first iteration will print 1 and not 0 as it would with .enumerate().
This newly suggested code is off by one as can be seen here:

pub fn main() {
    let mut i = 0;
    let v = vec!["a", "b", "c"];
    for (x, _) in v.iter().enumerate() {
        i += 1;
        println!("i is {} but x is {}", i, x)
    }
}
i is 1 but x is 0
i is 2 but x is 1
i is 3 but x is 2

clippy 0.0.212 (fb1dc34 2020-09-21)

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