Skip to content

New Lint: Use question mark instead of Option::and_then #6436

@camsteffen

Description

@camsteffen

What it does

Detect functions that end with Option::and_then or Result::and_then and suggest using a question mark instead.

Categories

  • Kind: style, maybe pedantic

It is simpler and more idiomatic.

Drawbacks

None.

Example

fn test(opt: Option<i32>) -> Option<i32> {
    opt.and_then(|n| {
        if n > 1 {
            Some(n + 1)
        } else {
            None
        }
    })
}

Could be written as:

fn test(opt: Option<i32>) -> Option<i32> {
    let n = opt?;
    if n > 1 {
        Some(n + 1)
    } else {
        None
    }
}

The and_then call should be the very last expression of the function (not inside an if block, for example).

More Questionable Cases

Single expression lambda (no block)

fn test(opt: Option<i32>) -> Option<i32> {
    opt.and_then(|n| foo(n))
}

At the end of a call chain

fn foo() -> Option<i32> {
    vec![1, 2, 3]
       .iter()
       .last()
       .and_then(|n| {
           // ...
       })
}

Personally I think those cases should still be linted. Maybe it can be configurable.

Metadata

Metadata

Assignees

Labels

A-lintArea: New lintsL-styleLint: Belongs in the style lint groupT-middleType: Probably requires verifiying typesgood first issueThese issues are a good way to get started with Clippy

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions