Rs
Module 3Enums & matchLesson 6 of 924 min

Option Deep Dive

Some/None, map, unwrap_or, if let — no more null crashes.

Option<T>

rust
enum Option<T> {
    None,
    Some(T),
}

Everyday combinators

rust
find("IBM").unwrap_or(0.0);
find("AAPL").map(|p| p * 10.0); // Option notional
find("X").is_some();

if let

rust
fn find(sym: &str) -> Option<f64> {
    match sym {
        "MSFT" => Some(412.55),
        _ => None,
    }
}

fn main() {
    if let Some(px) = find("MSFT") {
        println!("{px}");
    }
}
Output
412.55

Finance examples

  • Missing marks for a symbol
  • Optional stop trigger
  • Holiday calendar: no expiry date

Avoid unwrap in libraries

unwrap panics — fine in experiments, bad in pricing servers. Prefer ?, unwrap_or, or explicit match.

Challenge

Implement require_price(t) -> Result<f64, String> via ok_or.

Tips
  • Option is an enum
  • map transforms inside Some
  • unwrap_or provides defaults intentionally

Try it live

Option Deep DiveRust 2021
Loading editor…
Output
Press Run to compile and execute.