typestar

Option combinators in Rust

Working inside an Option instead of unwrapping it at every step.

fn main() {
    let raw: Option<&str> = Some("42");

    let doubled = raw
        .and_then(|s| s.parse::<i32>().ok())
        .map(|n| n * 2)
        .filter(|n| *n > 50);
    println!("{:?}", doubled);

    let missing: Option<i32> = None;
    println!("{}", missing.unwrap_or(0));
    println!("{}", missing.unwrap_or_else(|| 7 * 6));
    println!("{}", missing.unwrap_or_default());
    println!("{:?}", raw.or(Some("fallback")));
}

How it works

  1. map transforms the value and leaves None alone.
  2. and_then chains another Option-returning call.
  3. unwrap_or_else supplies a value only when needed.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
381
Tokens
152
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 96 seconds.

Type this snippet

Step 2 of 3 in Option, step 2 of 15 in Error handling.

← Previous Next →