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

`while_let_loop` suggests wrong name to use in pattern

Open domenicquirl opened this issue 4 years ago • 1 comments

When running clippy on this code

fn foo() -> Option<usize> {
    todo!()
}

fn main() {
    loop {
        let x = match foo() {
            Some(n) => n,
            None => break,
        };
        println!("{}", x);
    }
}

it (rightly) suggests that while let could be used instead. However, the suggested fix is try: 'while let Some(n) = foo() { .. }' (playground link), taking the n from the pattern inside the match instead of the x from let x. Carrying out this replacement introduces compilation errors, as x is now undefined.

Expected behaviour:

Suggest trying while let Some(x), taking the variable name that binds the result of the match expression.

Meta

  • cargo clippy -V: clippy 0.1.52 (9bc8c42b 2021-05-09)
  • rustc -Vv:
    rustc 1.52.1 (9bc8c42bb 2021-05-09)
    binary: rustc
    commit-hash: 9bc8c42bb2f19e745a63f3445f1ac248fb015e53
    commit-date: 2021-05-09
    host: x86_64-pc-windows-msvc
    release: 1.52.1
    LLVM version: 12.0.0
    

domenicquirl avatar Jun 16 '21 17:06 domenicquirl

This is basically the same issue as https://github.com/rust-lang/rust-clippy/issues/675, and that is why ellipsis are used in the first place.

For reference, the fix of #675:

LL | /     loop {
LL | |         let (e, l) = match "".split_whitespace().next() {
LL | |             Some(word) => (word.is_empty(), word.len()),
LL | |             None => break,
...  |
LL | |         let _ = (e, l);
LL | |     }
   | |_____^ help: try: `while let Some(word) = "".split_whitespace().next() { .. }`

kraktus avatar Sep 04 '22 20:09 kraktus