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

`while_let_loop` proposes replacing exhaustive matches with non-exhaustive ones (which is bad)

Open kpreid opened this issue 2 months ago • 3 comments

Summary

The while_let_loop lint proposes turning code that exhaustively matches the input into code that matches exactly one pattern and treats all values that do not match the pattern as equal reasons to stop. This means that the replacement code is more likely to become incorrect later, in the case that additional possible values (e.g. enum variants) are added to the scrutinee type. It is also potentially less clear about what specific situations will cause the loop to stop.

I think that this lint‘s scope should be reconsidered. Possibly it should be removed entirely, or possibly it should be narrowed to apply to patterns that are well-known to have exactly one non-matching value, such as Some(x) or Poll::Ready(x).

Lint Name

while_let_loop

Reproducer

I tried this code:

pub enum Error {
    Foo,
    // TODO: Add this variant
    // Bar,
}

pub fn example(mut f: impl FnMut() -> Result<(), Error>) {
    loop {
        match f() {
            Ok(()) => println!("success!"),
            Err(Error::Foo) => break,
        }
    }
}

I saw this happen:

warning: this loop could be written as a `while let` loop
  --> src/lib.rs:8:5
   |
 8 | /     loop {
 9 | |         match f() {
10 | |             Ok(()) => println!("success!"),
11 | |             Err(Error::Foo) => break,
12 | |         }
13 | |     }
   | |_____^ help: try: `while let Ok(()) = f() { .. }`

Note that the replacement will continue to compile when the Bar variant is added to the enum, whereas the original code would, correctly, stop compiling so that the author can consider how to handle that variant.

Version

rustc 1.101.0-nightly (0abfedbc7 2026-10-02)
binary: rustc
commit-hash: 0abfedbc7cd4e725f126913880c95800394f7c37
commit-date: 2026-10-02
host: aarch64-apple-darwin
release: 1.101.0-nightly
LLVM version: 23.1.1

Additional Labels

No response

kpreid avatar Oct 03 '26 05:10 kpreid

@rustbot claim

NullSpaceBoy avatar Oct 04 '26 16:10 NullSpaceBoy

I am planning on restricting the lint to only work with:

match x {
    Variant1 => {...}
    _ => break
}

and treating Option and Poll as special cases. Is this a good approach or is there something else I should look into?

NullSpaceBoy avatar Oct 09 '26 10:10 NullSpaceBoy

I think that sounds like a good approach.

kpreid avatar Oct 09 '26 14:10 kpreid