Skip to content

while_let_on_iterator Suggesting invalid Code With Refutable Pattern #5577

@ironhaven

Description

@ironhaven

When using a while let loop to get the results from the windows function clippy suggests that the while let be replaced with a regular for loop but a regular for loop will not compile because the pattern matches against a slice which has more possibilities.

Code

fn main() {
    let list = ["nail", "shoe", "horse"];
    let mut buf = String::new();
    let mut windows = list.windows(2);
    while let Some([first, second]) = windows.next() {
    //for [first, second] in windows {
     buf.push_str(&format!(
            "For want of a {} the {} was lost.\n",
            first, second
        ));
    }
    print!("{}", buf);
}

Clippy Output

warning: this loop could be written as a `for` loop
 --> src/lib.rs:4:39
  |
4 |     while let Some([first, second]) = windows.next() {
  |                                       ^^^^^^^^^^^^^^ help: try: `for [first, second] in windows { .. }`
  |
  = note: `#[warn(clippy::while_let_on_iterator)]` on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#while_let_on_iterator

Version

I can replicate with the clippy on the rust playground and my local clippy (clippy 0.0.212 (6651c1b 2020-04-15)
Playground Link

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions