rust-lang / rust-lang/rust-clippy
Suggest using a range iterator instead of casting `enumerate()`
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
Iterator::enumerate() is not the only way to produce an ascending sequence of indices; (0..) does as well, and can be combined with zip() to get the same output of pairs. This can be useful when an index of a type other than usize is needed. The lint should suggest using (0..).zip(iter) over iter.enumerate() in cases where the index produced by enumerate() is immediately converted to another type which implements core::iter::Step.
Advantage
- Simpler code.
- Avoids creating a value of the wrong type before the correct type.
- Avoids introducing a variable or repeated code if the typed index needs to be used more than once.
Drawbacks
- Could be considered to hide the possibility of overflow, though neither version is correct in that case.
enumerate()is a familiar operation, and sozip()ping an unbounded range may be less obvious.
Example
pub fn example1(data: &mut [Vec<u8>]) {
for (i, v) in data.iter_mut().enumerate() {
v.push(i as u8);
}
}
Could be written as:
pub fn example2(data: &mut [Vec<u8>]) {
for (i, v) in (0..).zip(data.iter_mut()) {
v.push(i);
}
}
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 with the enumerate() and (0..) examples in the issue, then locate the relevant Clippy lint entry points for enumerate indices and immediate casts. Review how comparable lint suggestions are tested; done means the lint identifies the described conversions and suggests the equivalent typed range zip without changing unrelated cases.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100