rust-lang / rust-lang/rust-clippy

Suggest using find rather than implementing it using a for loop

Open
#7,143 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint E-medium
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()
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=80518a6a20d1a57658a6c72bd7967a44

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.