rust-lang / rust-lang/rust-clippy

while_let_loop false positive

Open
#1,693 3 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug E-medium I-false-positive T-middle
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

fn main() {
    let mut lines = "foo".lines().peekable();
    // Gather remaining non-empty lines into a comment field.
    let mut comment = String::new();
    loop {
        if let Some(line) = lines.peek() {
            if line.is_empty() {
                break;
            } else {
                comment += line;
            }
        } else {
            break;
        }
        // Consume
        lines.next();
    }
}
warning: this loop could be written as a `while let` loop
  --> src/main.rs:5:5
   |
5  | /     loop {
6  | |         if let Some(line) = lines.peek() {
7  | |             if line.is_empty() {
8  | |                 break;
...  |
16 | |         lines.next();
17 | |     }
   | |_____^
   |
   = note: #[warn(while_let_loop)] on by default
help: try
   |     while let Some(line) = lines.peek() { .. }

This can't be trivially transformed into while let, since lines.next() is called unconditionally outside of the if let statement.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the warning with the Rust example in the issue and inspect the implementation of the while_let_loop lint. Trace why the unconditional lines.next() is treated as compatible with the suggested rewrite. Done means this example no longer receives an invalid while let suggestion, with regression coverage for the reported pattern.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.