Rust

Option Combinators (no unwrap!)

admin by @admin ADMIN
2d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`Option<T>` has a rich combinator API that lets you avoid both `unwrap()` and the verbose `match`. Chain `map`, `and_then`, `unwrap_or`, `or_else` to compose fallible operations.
Rust
Raw
fn main() {
    let n = Some(5);

    // map — transform the inner value, leave None alone
    println!("{:?}", n.map(|x| x * 2));               // Some(10)
    println!("{:?}", None::<i32>.map(|x| x * 2));     // None

    // and_then — flatMap; lets the closure return another Option
    let parsed: Option<i32> = "42".parse().ok();
    let plus_one = parsed.and_then(|n| n.checked_add(1));
    println!("{:?}", plus_one);                       // Some(43)

    // unwrap_or / unwrap_or_else — supply a fallback
    let v: Option<i32> = None;
    println!("{}", v.unwrap_or(0));                   // 0
    println!("{}", v.unwrap_or_else(|| expensive())); // 99 (only called if None)

    // filter — keep Some only if predicate holds
    println!("{:?}", Some(7).filter(|&x| x > 10));    // None
}

fn expensive() -> i32 { 99 }
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.