Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ MODEL THE DOMAIN
BUILD NOTE 18 / 53

Missing is a real case.

Express absence directly instead of using sentinel values.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

01 Understand the contract

Option<T> is either Some(T) or None. It distinguishes a present value from absence without borrowing a magic integer or empty string for that role. match and if let let you handle the variants. map transforms the present case, and_then chains optional operations, and unwrap_or supplies a fallback. Use unwrap only where an invariant justifies a panic; user input and lookup misses normally deserve a handled result. An Option<&T> can represent a borrowed lookup without cloning.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/option/src/main.rs
fn main() {
    let values = [10, 20];
    let doubled = values.get(1).map(|value| value * 2);
    println!("present={doubled:?}");
    println!("fallback={}", values.get(8).copied().unwrap_or(0));
    if let Some(first) = values.first() {
        println!("first={first}");
    }
}
↳ EXPECTED OUTPUT
present=Some(40)
fallback=0
first=10
  1. 1

    get returns an optional borrowed element.

  2. 2

    map transforms only the Some case.

  3. 3

    copied converts Option<&i32> to Option<i32> before applying a fallback.

From the extracted rust-workbench folder
cargo run -p lesson_option

03 Mind the boundary

04 Your next build

A SMALL MISSION

Return the first nonempty string from a slice, borrowing the text.

Reveal one possible solution +
solutions/option/src/main.rs
fn first_nonempty(values: &[String]) -> Option<&str> {
    values.iter().find(|s| !s.is_empty()).map(String::as_str)
}
fn main() {
    assert_eq!(first_nonempty(&[]), None);
    let v = vec![String::new(), "ready".into()];
    assert_eq!(first_nonempty(&v), Some("ready"));
}

05 Check your reasoning

QUICK SIGNAL CHECK

Which variant represents absence?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.