`Option`
Option<T> is Some(T) or None. It is Rust's replacement for null: a value that might be missing, with the compiler requiring you to say what happens when it is.
Detailed Explanation
Option<T> is an enum. Some(value) holds a T. None holds nothing. There is no hidden null pointer on every reference. A T is always present. An Option<T> is the type you use when absence is part of the contract: a lookup, a parent pointer, a first element of an empty list.
The compiler will not let you use the inner T without opening the enum. maybe.name does not compile. You match, if let Some(x) = maybe, maybe.unwrap(), maybe.unwrap_or(default), maybe.map(...), or maybe.ok_or(err)?. Each of those is an explicit choice. unwrap is the one that panics on None. It is for tests, for invariants you can prove, and for prototypes. It is not for a missing query parameter from the network.
Option implements a large method set that replaces small matches. map transforms the inner value. and_then chains a function that itself returns Option (flat-map). or_else supplies a fallback that is only computed on None. take moves the value out of a &mut Option and leaves None. as_ref turns &Option<T> into Option<&T> so you can match without moving.
Niche optimisation makes Option<&T>, Option<Box<T>>, and Option<fn()> the same size as the inner pointer. None is the null bit pattern, and you still cannot touch a T when it is None. Option<u32> is larger than u32 because every u32 bit pattern is valid.
Option is not Result. Absence is not an error. A user that has no middle name is None. A file that failed to open is Err. Using Option for I/O failures throws the reason away; using Result for a missing middle name implies something went wrong.
When you write Option: a value that may legitimately be missing. When you write Result: a computation that may fail with a reason. When you write T alone: the value is always there, and you want the compiler to believe that.
Code Examples
fn first_port(ports: &[u16]) -> Option<u16> {
ports.first().copied()
}
fn main() {
let port = first_port(&[8080, 8081]).unwrap_or(80);
println!("{port}"); // prints: 8080
let missing = first_port(&[]);
println!("{:?}", missing.map(|p| p + 1)); // prints: None
}Common Gotchas
You cannot use `T` through an `Option<T>`
There is no auto-unwrap. Match, `?` (in a function that returns `Option`), or a helper method.
`unwrap` panics on `None`
The message is `called Option::unwrap() on a None value`. Use `expect("why this cannot be None")` if you must, so the panic explains itself.
`as_ref` before match when you need the Option later
`match maybe { Some(x) => ... }` moves. `maybe.as_ref()` borrows.
Do not use `Option` as a failed `Result`
You lose the error. Map with `ok_or` or `ok_or_else` at the boundary if you need to start propagating.