Skip to content

Wrong while_let_on_iterator suggestion #3670

Closed
@jsgf

Description

@jsgf

In this code:

pub fn arg_value<'a>(
    args: impl IntoIterator<Item = &'a String>,
    find_arg: &str,
    pred: impl Fn(&str) -> bool,
) -> Option<&'a str> {
    let mut args = args.into_iter().map(String::as_str);

    while let Some(arg) = args.next() {
        let arg: Vec<_> = arg.splitn(2, '=').collect();
        if arg.get(0) != Some(&find_arg) {
            continue;
        }

        let value = arg.get(1).cloned().or_else(|| args.next());
        if value.as_ref().map(|p| pred(p)).unwrap_or(false) {
            return value;
        }
    }
    None
}

Clippy warns:

warning: this loop could be written as a `for` loop
  --> src/lib.rs:10:27
   |
10 |     while let Some(arg) = args.next() {
   |                           ^^^^^^^^^^^ help: try: `for arg in args { .. }`
   |
   = 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

However this is wrong because args.next() is called again within the body of the loop. Applying this suggestion would not compile.

Clippy gets this right in a simpler case, but I haven't tried to minimize this test case further.

This repos in current stable and nightly clippy:
clippy 0.0.212 (b2601be 2018-11-27)
clippy 0.0.212 (1b89724 2019-01-15)

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