RS.CLIPPY.RETURN_AND_THEN

Using `Option::and_then` or `Result::and_then` to chain a computation that returns an `Option` or a `Result`

This checker is a Clippy lint created by The Rust Project Contributors. The documentation shown here is a copy of the original documentation for: return_and_then. Copyright ©2025 The Rust Team. All rights reserved.

What it does

Detect functions that end with Option::and_then or Result::and_then, and suggest using the ? operator instead.

Why is this bad?

The and_then method is used to chain a computation that returns an Option or a Result. This can be replaced with the ? operator, which is more concise and idiomatic.

Example

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

Use instead:

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