Skip to content

while_let_on_iterator causes compile error #5844

@JarredAllen

Description

@JarredAllen

With this code:

let nums = vec![1, 2, 3, 4, 5, 1, 2, 3, 4, 5];
let mut iter = nums.iter().peekable();
while iter.peek().is_some() {
    while let Some(&next_elem) = iter.next() {
        if next_elem == 2 {
            break;
        }
    }
}

I expected to see this happen: No suggestion or a suggestion which doesn't cause a compile error

Instead, this happened: Clippy makes this suggestion which causes a compile error:

let nums = vec![1, 2, 3, 4, 5, 1, 2, 3, 4, 5];
let mut iter = nums.iter().peekable();
while iter.peek().is_some() {
    for &next_elem in iter {
        if next_elem == 2 {
            break;
        }
    }
}

which leads to the following compilation error

error[E0382]: borrow of moved value: `iter`
  --> src/main.rs:16:11
   |
15 |     let mut iter = nums.iter().peekable();
   |         -------- move occurs because `iter` has type `std::iter::Peekable<std::slice::Iter<'_, i32>>`, which does not implement the `Copy` trait
16 |     while iter.peek().is_some() {
   |           ^^^^ value borrowed here after move
17 |         for &next_elem in iter {
   |                           ----
   |                           |
   |                           value moved here, in previous iteration of loop
   |                           help: consider borrowing to avoid moving into the for loop: `&iter`

error: aborting due to previous err

Following that suggestion by borrowing there doesn't fix the issue, as it then suggests you remove the borrow due to &iter not being an iterable.

However, borrowing mutably (adding &mut) results in code which compiles and passes clippy. It would be nice if clippy could have this &mut in the original suggestion (though I don't know enough about the borrow checker to know how easy that would be to implement).

Here it is on the playground

Meta

  • cargo clippy -V: clippy 0.0.212 (5c1f21c 2020-07-13)
  • rustc -Vv:

rustc 1.45.0 (5c1f21c3b 2020-07-13)
binary: rustc
commit-hash: 5c1f21c3b82297671ad3ae1e8c942d2ca92e84f2
commit-date: 2020-07-13
host: x86_64-unknown-linux-gnu
release: 1.45.0
LLVM version: 10.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingC-enhancementCategory: Enhancement of lints, like adding more cases or adding help messagesI-false-positiveIssue: The lint was triggered on code it shouldn't haveI-suggestion-causes-errorIssue: The suggestions provided by this Lint cause an ICE/error when appliedL-suggestionLint: Improving, adding or fixing lint suggestionsT-MIRType: This lint will require working with the MIR

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions