Skip to content

needless_borrow suggestion doesn't compile #8367

@smoelius

Description

@smoelius

Summary

On the most recent nightly, the needless_borrow lint produces a suggestion that doesn't compile.

cargo +nightly-2022-01-29 clippy triggers this bug, but cargo +nightly-2022-01-28 clippy does not.

cc: @Jarcho (maybe?)

Reproducer

I tried this code:

fn main() {
    let s0 = String::new();
    let mut chars = s0.chars();
    let s1 = (&mut chars).take(0).collect::<String>();
    println!("{}", s1);
    drop(chars);
}

I expected to see this happen:

Nothing.

Instead, this happened:

warning: this expression borrows a value the compiler would automatically borrow
 --> src/main.rs:4:14
  |
4 |     let s1 = (&mut chars).take(0).collect::<String>();
  |              ^^^^^^^^^^^^ help: change this to: `chars`
  |
  = note: `#[warn(clippy::needless_borrow)]` on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow

If you make the suggested change, you get:

error[E0382]: use of moved value: `chars`
    --> src/main.rs:6:10
     |
3    |     let mut chars = s0.chars();
     |         --------- move occurs because `chars` has type `Chars<'_>`, which does not implement the `Copy` trait
4    |     let s1 = chars.take(0).collect::<String>();
     |                    ------- `chars` moved due to this method call
5    |     println!("{}", s1);
6    |     drop(chars);
     |          ^^^^^ value used here after move
     |
note: this function takes ownership of the receiver `self`, which moves `chars`
    --> /home/smoelius/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:1317:13
     |
1317 |     fn take(self, n: usize) -> Take<Self>
     |             ^^^^

Version

rustc 1.60.0-nightly (e0a55f449 2022-01-28)
binary: rustc
commit-hash: e0a55f4491a729bffc63b402ba903d90858c806b
commit-date: 2022-01-28
host: x86_64-unknown-linux-gnu
release: 1.60.0-nightly
LLVM version: 13.0.0

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thing

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions