rust-lang / rust-lang/rust-clippy
Suggest using find rather than implementing it using a for loop
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
Suggests replacing a for loop that searches for an item in an iterable, with the find iterator method.
Categories (optional)
- Kind: correctness
It's easier to make mistakes in a manual implementation. Using find is simpler and easier to maintain, focusing the attention on the predicate.
Drawbacks
Suggestions might not work in complex edge cases.
If the lookup does a mapping, it might be harder to create a good suggestion. If the lookup finds an index, we should suggest Iterator::index instead of find.
Example
const ARRAY: &[u32; 5] = &[2, 7, 1, 9, 3];
fn lookup(n: u32) -> Option<u32> {
for &v in ARRAY {
if v == n {
return Some(v);
}
}
None
}
Could be written as:
const ARRAY: &[u32; 5] = &[2, 7, 1, 9, 3];
fn lookup(n: u32) -> Option<u32> {
ARRAY.iter().find(|&&v| v == n).cloned()
}
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 from the issue's Rust examples and compare the manual lookup with Iterator::find, including the noted mapping and index cases. Determine which loop shapes are safe to suggest and how the lint should avoid complex edge cases; done means the supported patterns produce correct suggestions without changing behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100