rust-lang / rust-lang/rust-clippy

remove nesting for `if let else None`

Open
#7,697 2 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

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

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 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.