Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wrong while_let_on_iterator suggestion #3670

Closed
jsgf opened this issue Jan 18, 2019 · 1 comment
Closed

Wrong while_let_on_iterator suggestion #3670

jsgf opened this issue Jan 18, 2019 · 1 comment

Comments

@jsgf
Copy link
Contributor

jsgf commented Jan 18, 2019

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)

@jsgf
Copy link
Contributor Author

jsgf commented Jan 18, 2019

I'm not sure if this is a dup of #1033

bors added a commit that referenced this issue Jan 19, 2019
Fix bad `while_let_on_iterator` suggestion.

Don't suggest a `for` loop if the iterator is used inside the `while` loop.

Closes #3670
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant