rust-lang / rust-lang/rust-clippy
suggest .into_iter() instead of .iter() on containers if it's possible to remove clones?
Open
Nobody has claimed this yet.
L-perf
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
fn main() {
let v = vec![String::new(); 10];
let bla: Vec<_> = v
.iter() // over the vector
.map(|s| {
let v = s.clone().into_bytes();
// because "into_bytes() consumes s, we have to clone() s here
v.len();
v
})
.collect();
// but in the end, v is no longer used
}
So we can rewrite this example to use .into_iter() instead of .iter() which has the 'advantage' of of consuming bla. This makes it clear that since we consume the vector, we can also safely consume the contained items and lets us remove the clone:
fn main() {
let v = vec![String::new(); 10];
let bla: Vec<_> = v
.into_iter() // consume the vec
.map(|s| {
let v = s.into_bytes(); // consuming s is ok now.
v.len();
v
})
.collect();
// v has no use so it's save for consumption, nom
}
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 comparing the two Rust examples and define when replacing .iter() with .into_iter() is safe and removes the clone. Done means Clippy can identify applicable container iterations, suggest the consuming form, and avoid suggesting it when the container or its elements are still needed.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- devtools
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100