Sub topic 2
Option<T>: a value that may be missing
This chapter covers how Option<T> is defined, how you create and inspect one, and the mistakes people commonly make with it. It assumes you know basic Rust syntax, enums and match, ownership and borrowing, and generics at a conceptual level. The previous chapter explained why Rust has no null. This one looks at what it uses instead.
What Option is
Option<T> is an ordinary enum from the standard library. It has two variants: Some(T) holds a value, and None holds nothing. Both variants are in the prelude, so you write Some(5) and None without a use line.
The type is not special syntax. The next example defines the same shape under another name, so you can see there is no hidden machinery.
enum Maybe<T> {
Nothing,
Just(T),
}
fn main() {
let a: Maybe<i32> = Maybe::Just(3);
let b: Maybe<i32> = Maybe::Nothing;
for m in [a, b] {
match m {
Maybe::Just(n) => println!("just {n}"),
Maybe::Nothing => println!("nothing"),
}
}
}The standard Option<T> is the same declaration with the names None and Some. The difference is the large set of methods defined on it, which later chapters cover.
Why the type matters
A value of type i32 is always an integer. A value of type Option<i32> is a different type, and the compiler will not let you use it as an i32. To get the integer out, you must say what happens when it is missing. In languages with null, any reference may be null, so every dereference is a possible crash. In Rust the possibility of absence appears in the type, and only where it can actually occur.
Creating Options
You usually get an Option from a function that may not have an answer. You can also write one yourself. The function below searches a slice for the first even number.
fn first_even(nums: &[i32]) -> Option<i32> {
nums.iter().copied().find(|n| n % 2 == 0)
}
fn main() {
match first_even(&[1, 3, 4, 5]) {
Some(n) => println!("found {n}"),
None => println!("no even number"),
}
println!("{:?}", first_even(&[1, 3, 5]));
}The first call prints found 4. The second prints None. The signature tells every caller that "no even number" is a normal outcome, not an accident.
Many standard library methods return Option:
slice.first(),slice.last(), andslice.get(i)returnNonewhen the slice is empty or the index is out of range.iterator.next()returnsNonewhen the iterator is exhausted.map.get(key)returnsNonewhen the key is absent.str.find(pat)returnsNonewhen the pattern does not occur.
Option holds references too
HashMap::get does not return Option<V>. It returns Option<&V>, a borrowed view of the stored value, because returning the value itself would require moving or cloning it out of the map. The reference keeps the map borrowed for as long as it lives.
use std::collections::HashMap;
fn main() {
let mut stock: HashMap<&str, u32> = HashMap::new();
stock.insert("apples", 12);
let apples: Option<&u32> = stock.get("apples");
let pears = stock.get("pears");
println!("{apples:?} {pears:?}");
println!("{}", stock.get("apples").copied().unwrap_or(0));
println!("{}", stock.contains_key("pears"));
}This prints Some(12) None, then 12, then false. The copied() call turns Option<&u32> into Option<u32> for types that implement Copy. For types that do not, cloned() does the same by cloning. A later chapter covers as_ref, as_mut, and take, which handle the same borrowing problem for an Option you own.
Inspecting an Option without matching
Sometimes you only need a yes or no answer.
is_some()returnstrueforSome.is_none()returnstrueforNone.is_some_and(|v| ...)returnstruewhen the value is present and the closure returnstrue. It has been stable since Rust 1.70.
Option<T> implements PartialEq whenever T does, so you can compare against a literal Some. It also implements PartialOrd when T does, and None sorts before every Some.
fn main() {
let x: Option<i32> = Some(5);
let y: Option<i32> = None;
println!("{} {}", x.is_some(), y.is_none());
println!("{}", x.is_some_and(|n| n > 3));
println!("{}", x == Some(5));
println!("{}", y < Some(i32::MIN));
}The output is true true, then true, true, true.
Type inference and None
Some(5) tells the compiler that T is an integer type. None carries no value, so the compiler cannot infer T from it alone. Without a hint you get a "type annotations needed" error. You can supply the hint with a type annotation or with the turbofish syntax.
use std::mem::size_of;
fn main() {
let nothing: Option<u8> = None;
let also = None::<u8>;
println!("{nothing:?} {also:?}");
assert_eq!(size_of::<Option<&i32>>(), size_of::<&i32>());
assert_eq!(size_of::<Option<Box<i32>>>(), size_of::<Box<i32>>());
assert!(size_of::<Option<i32>>() > size_of::<i32>());
println!("ok");
}The assert lines show a point about cost. References and Box can never be null, so the compiler uses the null address to represent None. This is called the niche optimization. Option<&T> and Option<Box<T>> take no more memory than the plain pointer. For i32, every bit pattern is a valid number, so Option<i32> needs an extra tag and becomes larger. Either way, you pay no runtime cost for safety on pointer types.
Common errors
Most mistakes with Option come from treating it as the inner value.
| Mistake | What happens | Fix |
|---|---|---|
| `let n: i32 = first_even(&v);` | Type mismatch. `Option<i32>` is not `i32`. | Match, or use a default with `unwrap_or`. |
| `first_even(&v) + 1` | No `Add` implementation for `Option<i32>`. | Extract the value first, or use `map`. |
| `let x = None;` and nothing else | "Type annotations needed". | Write `let x: Option<T> = None;`. |
| Calling `unwrap()` to silence the compiler | A panic at runtime when the value is `None`. | Handle `None`, or use `expect` with a reason. |
| Returning `Some(x)` from a branch and nothing from another | Mismatched branch types. | Return `None` from the other branch. |
| Using `Option<Option<T>>` by accident | You must unwrap two layers. | Use `flatten()` or `and_then` instead of `map`. |
Each error message points at a type mismatch. This is the compiler enforcing the rule that absence must be handled.
When Option is the right choice
Use Option when "no value" is a normal, expected outcome and needs no explanation. A search that finds nothing is a good example. If the caller would want to know why the value is missing, such as a parse failure or a missing file, use Result instead. The next chapter covers it.
A few related guidelines:
- Do not use sentinel values such as
-1or an empty string to mean "missing".Optionmakes the case explicit. - Struct fields that may be unset should be
Option<T>, not a placeholder default. - A function that always returns a value should not return
Optionjust in case. Extra layers add work for every caller.
Exercises
Exercise
A function returns Option<usize> from "hello".find('z'). What value does it return, and why can you not write let i: usize = "hello".find('z');?
Show answer
It returns None, because the character z does not appear in the string. The binding fails to compile because Option<usize> and usize are different types. The compiler requires you to decide what happens in the None case, for example with match, unwrap_or(0), or an early return.
Exercise
Why is size_of::<Option<Box<i32>>>() equal to size_of::<Box<i32>>(), but size_of::<Option<i32>>() larger than size_of::<i32>()?
Show answer
A Box is never null, so the compiler stores None as the null pointer and needs no extra space. Every bit pattern of an i32 is a valid integer, so no spare pattern exists, and Option<i32> needs an additional tag to tell Some from None.