rust-lang / rust-lang/rust-clippy
Suggest `and_then`
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
If there is a callback that takes a type T and returns Option<U> (or Cb: Fn(T) -> Option<U>), if we have type Option<T>, we should prefer opt_t.and_then(cb), and not opt_t.map(cb). This means the result will be Option<U> and not Option<Option<U>>.
Lint Name
option_map_option
Category
style
Advantage
It avoids nested pattern matching to resolve the nested options and/or results.
Drawbacks
Although unlikely, if there is an API that expected a nested option/result, then this could produce a spurious warning.
Example
pub fn map<T, U: Default, Cb: Fn(T) -> Option<U>>(opt: Option<T>, cb: Cb) -> U {
if let Some(u) = opt.map(cb) {
u.unwrap_or_default()
} else {
U::default()
}
}
Could be written as:
pub fn and_then<T, U: Default, Cb: Fn(T) -> Option<U>>(opt: Option<T>, cb: Cb) -> U {
opt.and_then(cb).unwrap_or_default()
}
The warning would be something like:
if let Some(u) = opt.map(cb) {
^^^^^^^^^^^ help: try this: `let u = opt.and_then(cb);`
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 issue's option_map_option lint proposal and compare the two Rust examples to clarify the intended warning and suggestion. Locate the existing lint implementation and tests for similar Option transformations, then add coverage showing the nested Option case and verify that the suggested and_then form avoids false positives.
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
- 45/100