rust-lang / rust-lang/rust-clippy
False Positive for needless_collect with two mutable borrows
Open
Nobody has claimed this yet.
C-bug
I-false-positive
L-nursery
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
Summary
The applied lint fails to compile due to a Map created with items created from mutable borrows.
Lint Name
clippy::needless_collect
Reproducer
I tried this code:
...
let v: Vec<char> = (0..num)
.map(|_| cmap.get_mut(origin - 1).unwrap().pop().unwrap())
.collect();
cmap.get_mut(target - 1)
.unwrap()
.extend(v.into_iter().rev());
...
}
I saw this happen:
warning: avoid using `collect()` when not needed
--> src\days\day_05.rs:28:18
|
28 | .collect();
| ^^^^^^^
...
31 | .extend(v.into_iter().rev());
| ------------- the iterator could be used here instead
|
= note: `#[warn(clippy::needless_collect)]` on by default
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_collect
help: use the original Iterator instead of collecting it and then producing a new one
|
26 ~
27 | cmap.get_mut(target - 1)
28 | .unwrap()
29 ~ .extend((0..num)
30 ~ .map(|_| cmap.get_mut(origin - 1).unwrap().pop().unwrap()).rev());
|
I expected to see this happen:
No warning.
Version
rustc 1.65.0 (897e37553 2022-11-02)
binary: rustc
commit-hash: 897e37553bba8b42751c67658967889d11ecd120
commit-date: 2022-11-02
host: x86_64-pc-windows-msvc
release: 1.65.0
LLVM version: 15.0.0
Additional Labels
No response
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the warning from the Rust snippet in the issue, focusing on the clippy::needless_collect lint and its suggested iterator rewrite. Trace how the lint handles the two mutable borrows; done means this valid pattern is no longer warned about while the lint still reports cases where collecting is unnecessary.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100