Option<T> (Rust)
Option<T> is Rust's replacement for null. It is an enum with two variants: Some(value) when a value is present, and None when it is absent. The compiler forces you to handle the missing case.
Rust
Rust has no null. Anything that might be absent is wrapped in Option<T>, so the type system makes the possibility of 'nothing' visible and impossible to ignore. This eliminates the null-pointer / NullPointerException class of bugs entirely.
You unwrap an Option safely with match, if let, or combinators like .map(), .unwrap_or(default), and the ? operator. Calling .unwrap() extracts the value but panics on None — fine for prototypes and tests, risky in production.
Option pairs with Result: use Option when absence is normal and not an error (a missing dictionary key), and Result when an operation can fail with a reason.
Syntax
let maybe: Option<i32> = Some(5);
let nothing: Option<i32> = None;Examples
Rust
fn main() {
let nums = vec![10, 20, 30];
match nums.get(1) {
Some(n) => println!("got {}", n),
None => println!("nothing"),
}
println!("{}", nums.get(9).unwrap_or(&0));
}Output:
got 20
0