Option<T> for explicit null handling

Marcus Chen Jan 2026
1 tab
fn divide(a: i32, b: i32) -> Option<i32> {
    if b == 0 {
        None
    } else {
        Some(a / b)
    }
}

fn main() {
    match divide(10, 2) {
        Some(result) => println!("Result: {}", result),
        None => println!("Cannot divide by zero"),
    }
}
1 file · rust Explain with highlit

Rust has no null. Instead, Option<T> represents a value that might be absent. It's an enum with two variants: Some(T) and None. You must explicitly handle both cases with match, if let, or combinator methods like .map() and .unwrap_or(). This eliminates null pointer exceptions at compile time. I use Option for optional struct fields, return values from lookups, and any value that might not exist. The ? operator works with Option too, propagating None early. The standard library provides rich combinators (.and_then(), .or_else(), .filter()) that let you chain transformations functionally. This design makes absence explicit and forces you to handle it correctly.