rust-lang / rust-lang/rust-clippy
Suggest implementing `Iterator::fold` and others when implementing `Iterator` for an enum
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
Suggest to implement optional methods when implementing Iterator for an enum.
From the iterator docs:
Also note that Iterator provides a default implementation of methods such as nth and fold which call next internally. However, it is also possible to write a custom implementation of methods like nth and fold if an iterator can compute them more efficiently without calling next.
This almost always important when implementing Iterator on an enum, as implementations of Iterator::next will almost always branch on the variant (and this variant is rather unlikely to change; if it does, the lint could not apply, but this seems rather uncommon).
The methods to be suggested could include nth and fold as suggested in the quote from the docs above, as well as any other methods that would do repeated branching.
Note that these situations are not always optimized by the compiler, see e.g. https://github.com/rust-lang/rust/issues/87950.
Categories
- Kind:
clippy::perf, as it helps the compiler optimize.
Drawbacks
None.
Example
enum MyEnum {
VariantOne,
VariantTwo,
}
impl Iterator for MyEnum {
...
}
Suggestion along the lines of:
"You're implementing Iterator on an enum. The default implementations of fold, nth and ... repeatedly call your implementation of next, which does a potentially expensive match. Consider implementing implementing these methods explicitly if you know your variant won't change."
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 reviewing the Iterator documentation section on implementing Iterator and the linked rust-lang/rust issue #87950. Define which repeated-branching methods, including nth and fold, the lint should suggest for enum iterators, and specify the diagnostic wording and applicability. Done means the proposed lint behavior and scope are implemented and covered by tests.
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