rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

Autofix `explicit_counter_loop` (MaybeIncorrect) produces invalid rust code.

Open iago-lito opened this issue 1 year ago • 1 comments

Description

Applying fix on this situation:

fn f(v: Vec<u64>) {
    let mut i = 0;
    for e in &v {  // consider using: `for (i, e) in v.iter().enumerate()`
        println!("{i}: {e}");
        i += 1;
    }
}

Produces the following:

fn f(v: Vec<u64>) {
    let mut i = 0;
    for (i, e) in v.iter().enumerate() {
        println!("{i}: {e}");
        i += 1; // /!\ cannot assign twice to immutable variable `i`
    }
}

I'm not sure whether this contradicts with the "should result in valid Rust code" part of the MaybeIncorrect marker for this lint (?), but possibly the orginal i variable should be removed by this autofix?

Version

rustc 1.84.0-nightly (da935398d 2024-10-19) binary: rustc commit-hash: da935398d582344c5b7689bd6632d8ec01b0c988 commit-date: 2024-10-19 host: x86_64-unknown-linux-gnu release: 1.84.0-nightly LLVM version: 19.1.1

Additional Labels

No response

iago-lito avatar Oct 20 '24 21:10 iago-lito

@rustbot label +I-suggestion-causes-error

alex-semenyuk avatar Oct 21 '24 08:10 alex-semenyuk

"Valid Rust code" refers to syntactic validity -- this is in contrast to HasPlaceholders, which, well, has placeholders in the suggestion, so that, if you were to paste in the suggestion verbatim, the resulting code would be syntactically invalid.

That said, I do agree that removing the counter automatically would be nice, so I'll turn this issue into an enhancement request.

@rustbot label -I-suggestion-causes-error +C-enhancement

ada4a avatar Sep 07 '25 14:09 ada4a