tezvyn:

Rust's Option<T>: Handling Absence Safely

AI-drafted, machine-checkedSource: doc.rust-lang.orgbeginner

Rust's Option<T> is a type-safe box that holds either a value (Some(T)) or nothing (None), eliminating null pointer errors. Use it for function returns that might fail or for optional struct fields. The footgun is `.unwrap()`, which panics on None.

WHY IT EXISTS Many languages use null to represent the absence of a value, which leads to runtime errors if not checked. Rust avoids this "billion-dollar mistake" by encoding absence into the type system itself. This forces the programmer to handle the possibility of a missing value at compile time, not at runtime.

THE MENTAL MODEL Think of an Option<T> as a sealed box. The box either contains exactly one item of type T (the Some(T) variant) or it is empty (the None variant). The compiler requires you to check if the box is empty before you can take the item out, preventing you from accidentally trying to use something that isn't there.

HOW IT WORKS Option<T> is an enum with two variants: Some(T) which wraps a value, and None which represents absence. Because it's an enum, you can use a match statement to exhaustively handle both cases. The compiler will issue an error if you fail to handle None, guaranteeing safety. For convenience, Rust provides many methods on Option, such as is_some(), map(), and unwrap_or(), to work with optional values more concisely.

WHEN TO USE IT Use Option<T> whenever a value might not exist. This is idiomatic for function return values that can fail (e.g., finding an item in a collection), for optional struct fields (e.g., a User struct where middle_name is optional), and for any variable that might not have a value yet. It is the default tool for handling nullability in Rust.

WHEN NOT TO USE IT Don't use Option<T> when a value is guaranteed to exist; just use the type T directly. For error handling where you need to know why an operation failed, the Result<T, E> enum is a better choice. Result can carry a descriptive error value E, whereas Option simply signifies presence or absence.

ONE CANONICAL EXAMPLE A function that divides two numbers must handle division by zero. Instead of crashing, it can return an Option<f64>. A call like safe_divide(10.0, 2.0) would return Some(5.0), while safe_divide(10.0, 0.0) would return None. The caller is then forced by the type system to handle the None case before using the result.

Read the original → doc.rust-lang.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.