Closed
Description
Summary
Clippy suggests removing a borrow that would lead to ownership being moved.
Lint Name
needless_borrow
Reproducer
I tried this code:
fn main() {
let mut iter = vec![1, 2, 3].into_iter();
let mut sum = 0;
for v in (&mut iter).enumerate().take(1) {
sum += v.1;
}
let b = iter.count();
}
I saw this happen:
warning: this expression borrows a value the compiler would automatically borrow
--> src/main.rs:65:14
|
65 | for v in (&mut iter).enumerate().take(1) {
| ^^^^^^^^^^^ help: change this to: `iter`
If we follow the lint:
fn main() {
let mut iter = vec![1, 2, 3].into_iter();
let mut sum = 0;
for v in iter.enumerate().take(1) {
sum += v.1;
}
let b = iter.count();
}
Our code does not compile:
error[E0382]: use of moved value: `iter`
--> src/main.rs:69:13
|
62 | let mut iter = vec![1, 2, 3].into_iter();
| -------- move occurs because `iter` has type `std::vec::IntoIter<i32>`, which does not implement the `Copy` trait
...
65 | for v in iter.enumerate().take(1) {
| ----------- `iter` moved due to this method call
...
69 | let b = iter.count();
| ^^^^ value used here after move
|
note: this function takes ownership of the receiver `self`, which moves `iter`
--> /home/ritchie46/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:928:18
|
928 | fn enumerate(self) -> Enumerate<Self>
| ^^^
Version
rustc 1.60.0-nightly (e7aca8959 2022-02-09)
binary: rustc
commit-hash: e7aca895980f25f6d2d3c48e10fd04656764d1e4
commit-date: 2022-02-09
host: x86_64-unknown-linux-gnu
release: 1.60.0-nightly
LLVM version: 13.0.0
Additional Labels
No response