How to Use Option<T> in Rust

The Complete Guide

Use Option<T> with match, if let, or let...else to safely handle values that might be missing without causing runtime errors.

Use Option<T> to represent a value that might be present (Some(value)) or absent (None), handling both cases with pattern matching.

fn plus_one(x: Option<i32>) -> Option<i32> {
    match x {
        None => None,
        Some(i) => Some(i + 1),
    }
}

let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);

Alternatively, use if let for concise handling when you only care about the Some case:

if let Some(desc) = describe_state_quarter(Coin::Quarter(UsState::Alaska)) {
    println!("{desc}");
}

Or use the let...else guard for early returns:

let Coin::Quarter(state) = coin else {
    return None;
};