typestar

Option in Rust

Representing a value that may be absent.

fn find_even(items: &[i32]) -> Option<i32> {
    items.iter().copied().find(|n| n % 2 == 0)
}

fn main() {
    let nums = [1, 3, 4, 7];
    let even = find_even(&nums);

    let doubled = even.map(|n| n * 2).unwrap_or(0);
    if let Some(v) = even {
        println!("found {v}");
    }
    println!("{doubled}");
}

How it works

  1. find returns Option<i32>, maybe nothing.
  2. map and unwrap_or transform or default it.
  3. if let Some(v) unwraps when present.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
279
Tokens
111
Three-star pace
95 tpm

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

Type this snippet

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

Next →