rust-lang / rust-lang/rust-clippy
remove nesting for `if let else None`
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
I see myself often writing something like this:
fn some_function<T>(some_option: Option<T>) -> Option<T> {
if let Some(value) = some_option {
// some code
} else {
None
}
}
this could be written as:
fn some_function<T>(some_option: Option<T>) -> Option<T> {
let value = some_option?;
// some code
}
which is a lot cleaner to read and removes one layer of nesting. I think clippy currently suggests calling Option::map:
fn some_function<T>(some_option: Option<T>) -> Option<T> {
some_option.map(|value| {
// some code
})
}
This is fine, but it has some disadvantages:
- it is harder to understand for newcomers
- and it introduces a new layer of nesting
Categories (optional)
- Kind:
clippy::style
What is the advantage of the recommended code over the original code
- less noise in the code
Drawbacks
Might conflict with existing lints.
Example
fn some_function<T: fmt::Display>(some_option: Option<T>) -> Option<String> {
if let Some(value) = some_option {
println!("{}", &value);
Some(value.to_string())
} else {
None
}
}
Could be written as:
fn some_function<T: fmt::Display>(some_option: Option<T>) -> Option<String> {
let value = some_option?;
println!("{}", &value);
Some(value.to_string())
}
(this is kind of a bad example, but I can not think of a better one at the moment)
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 Clippy's existing clippy::style lints and the current guidance around Option::map. Compare the proposed if-let/else pattern with the Option examples in the issue, including possible conflicts with existing lints. Done means the intended pattern and exclusions are defined and covered by appropriate lint tests.
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