rust-lang / rust-lang/rust-clippy
`iter.collect::<Vec<_>>().into_iter()` is useless and causes extra work
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
What it does
Given the pattern iter.collect::<Vec<_>>().into_iter() Clippy should recommend dropping the collect() and into_iter() calls as they cause useless allocations and work to build a Vec which is immediately iterated over and dropped.
I hit this as I wrote some code which was then refactored to introduce this useless Vec construction/destruction and it caused an OOM in production.
NOTE: This cannot be generalized to all collect() calls as some types will deduplicate when collected (e.g. HashSet)
Advantage
- Removes extra work
- Removes allocations (can prevent OOMs)
- Helps the programmer identify a likely mistake (e.g. during refactoring, which is how I hit this)
Drawbacks
This can't easily be generalized from Vec to all types as some types perform non-trivial work during collect() which could affect the subsequent iterator.
Example
let v: Vec<u8> = vec![1, 2, 3];
let v2: Vec<u8> = v.into_iter().collect::<Vec<u8>>().into_iter().map(|x| x * 2).collect();
Could be written as:
let v: Vec<u8> = vec![1, 2, 3];
let v2: Vec<u8> = v.into_iter().map(|x| x * 2).collect();
Comparison with existing lints
I can't find any lint that covers this exact case: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2024&gist=be7215aaba35a6e279eb551de374d578
Additional Context
Meta employees can see the additional discussion here where folks recommended to post here: https://fb.workplace.com/groups/rust.language/posts/30023410667280829/
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 Clippy's existing lint handling for collect and into_iter, then inspect how similar lints define diagnostics and tests. Reproduce the example and verify that the completed lint catches the Vec-specific pattern without generalizing to collections such as HashSet.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100