rust-lang / rust-lang/rust-clippy

Suggest to replace `Option.into_iter().filter_map(func).next()` with `Option.and_then(func)`

Open
#13,488 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

What it does

Somehow I always want to use filter_map with Option, and I always forget that it's equivalent to Option::and_then, so I end up doing this contrived way that uses a few functions. This lint would remind me that and_then exists and could and should be used in this case.

Advantage

Remove two intermediate function calls, with the complexity they entail, and use a more idiomatic Rust way.

Drawbacks

Maybe too targeted to my brain's dysfunctions 🤪

Example
let a_value = Some(42);
let x = a_value.into_iter().filter_map(|value| if value < 30 { Some(value + 13) } else { None }).next();

Could be written as:

let a_value = Some(42);
let x = a_value.and_then(|value| if value < 30 { Some(value + 13) } else { None });

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 with the Rust examples in the issue and inspect existing Clippy lint implementations and tests for similar Option or iterator simplifications. Confirm the lint should recognize the shown into_iter().filter_map(...).next() pattern and suggest and_then without broader matches. Done means the lint, its tests, and user-facing documentation cover the intended case.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.