rust-lang / rust-lang/rust-clippy
`needless_collect` has no understanding of lifetimes
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
Summary
needless_collect doesn't consider if the iterator is borrowing values that are moved between the collect call and where the collected values are used.
Lint Name
needless_collect
Reproducer
I tried this code:
fn main() {
let original = vec![1, 2];
let copied: Vec<_> = (&original).iter().copied().collect();
drop(original);
copied.into_iter().for_each(|e| println!("{e:?}"));
}
I saw this happen:
needless_collect suggests this code, which references original after I explicitly move it and the suggestion does not compile.
fn main() {
let original = vec![1, 2];
drop(original);
(&original).iter().copied().for_each(|e| println!("{e:?}"));
}
I expected to see this happen:
needless_collect should not fire here since originals is moved after the collect call but before the into_iter call that it wants to eliminate.
Version
rustc 1.62.0 (a8314ef7d 2022-06-27)
binary: rustc
commit-hash: a8314ef7d0ec7b75c336af2c9857bfaf43002bfc
commit-date: 2022-06-27
host: x86_64-unknown-linux-gnu
release: 1.62.0
LLVM version: 14.0.5
Additional Labels
@rustbot label I-suggestion-causes-error
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 locating the needless_collect lint implementation and its existing tests, then reproduce the issue with the Rust example in this report. Trace how the lint decides whether removing collect is safe when borrowed values are used after the collection, and add coverage showing that the lint does not fire after original is moved.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100