Sub topic 6
Option: handling absent values
This chapter assumes you can define enums, write match expressions, and read basic Rust function signatures. It covers how Option<T> represents a value that may be missing and how to handle it.
Why Rust has no null
Many languages use null to mean "no value". Any reference might be null, and forgetting to check it causes crashes at runtime. Rust has no null. Instead, the standard library defines an ordinary enum:
enum Option<T> {
Some(T),
None,
}Some(T) holds a value of type T. None holds nothing. Option and its variants are in the prelude, so you write Some(5) and None without a use statement.
An Option<i32> is a different type from an i32. You cannot add one to the other. You must first take the value out, and the compiler makes you decide what happens in the None case.
Returning an Option
Use Option<T> as a return type when a function may have no answer. This function finds the first even number in a slice:
fn first_even(nums: &[i32]) -> Option<i32> {
nums.iter().copied().find(|n| n % 2 == 0)
}
fn main() {
match first_even(&[1, 3, 4, 6]) {
Some(n) => println!("first even: {n}"),
None => println!("no even number"),
}
if let Some(n) = first_even(&[1, 3, 5]) {
println!("found {n}");
} else {
println!("nothing found");
}
}The program prints first even: 4 and then nothing found. The iterator method find already returns an Option, so the function passes it through.
The match must cover both Some and None, or the code will not compile. if let is shorter when you care about one case and want a simple fallback for the other.
Common ways to handle an Option
match is always available, but Option also has helper methods for frequent cases.
| Method | What it does |
|---|---|
| `unwrap_or(default)` | Returns the inner value, or `default` if `None` |
| `map(f)` | Applies `f` to the inner value and leaves `None` unchanged |
| `ok_or(err)` | Converts `Option<T>` to `Result<T, E>` |
| `is_some()` / `is_none()` | Returns a `bool` without extracting the value |
| `unwrap()` | Returns the inner value, or panics on `None` |
Here are a few of them together:
fn main() {
let name: Option<&str> = Some("ferris");
let missing: Option<&str> = None;
println!("{}", name.unwrap_or("anonymous"));
println!("{}", missing.unwrap_or("anonymous"));
let length = name.map(|s| s.len());
println!("{:?}", length);
}This prints ferris, anonymous, and Some(6).
Common errors
- Using
unwrap()on a value that can beNone. The program panics at runtime. Reserveunwrap()for tests, quick experiments, or cases where you have already proven the value exists. In other code, usematch,unwrap_or, or?. - Treating
Option<i32>likei32. An expression such asmaybe + 1fails with a type mismatch. Extract the value first, or usemaybe.map(|n| n + 1). - Forgetting the
Nonearm. The compiler reports a non-exhaustive match. Add aNonearm, or use_if every remaining case is handled the same way.
Exercise
Write a function last_word(s: &str) -> Option<&str> that returns the last whitespace-separated word of a string. What does it return for an empty string, and which standard methods would you use?
Show answer
Use s.split_whitespace().last(). split_whitespace yields the words as an iterator, and last() returns Some(word) for the final one or None when there are no words. For an empty string the function returns None. The full function is fn last_word(s: &str) -> Option<&str> { s.split_whitespace().last() }.