Sub topic 6
Option: handling absent values
What this chapter assumes
You should know how to define an enum, write a match over its variants, and read basic ownership errors such as "use of moved value". The previous chapters covered those topics. Here you will see how the standard library uses them to represent a value that might not exist.
The problem Option solves
Many languages use a special value such as null or nil to mean "nothing here". Any reference can be null, so any use of a reference can fail at run time. The compiler can't tell you which ones.
Rust has no null. A function that might not produce a value says so in its return type, and the compiler makes you deal with the missing case before you can use the value.
The definition
Option<T> is an ordinary enum in the standard library. It looks like this:
enum MyOption<T> {
None,
Some(T),
}
fn main() {
let present: MyOption<i32> = MyOption::Some(5);
let absent: MyOption<i32> = MyOption::None;
for opt in [present, absent] {
match opt {
MyOption::Some(n) => println!("got {n}"),
MyOption::None => println!("nothing"),
}
}
}The real type is Option<T> with variants Some(T) and None. The prelude imports all three names, so you write Some(5) and None without a path. T is a generic parameter. Option<i32> and Option<String> are different types.
An Option<i32> is not an i32. You can't add 1 to it, and you can't pass it where an i32 is expected. To get the inner value you must go through the Some variant, which forces you to consider None.
Producing Option values
Many standard library methods return Option when a result may not exist:
slice.first(),slice.get(i), andvec.pop()returnNonefor an empty or too-short collection.str.find(c)returnsNonewhen the character is absent.HashMap::get(&key)returnsNonefor a missing key.iter.find(...)anditer.next()returnNonewhen nothing matches or the iterator is exhausted.
Your own functions can do the same:
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 match must cover both variants. The if let handles one pattern and sends everything else to else. Use match when both branches matter equally. Use if let when you only care about Some.
.copied() turns an iterator of &i32 into an iterator of i32. Without it, find would return Option<&i32>.
Working with the value without writing match
Writing a match for every Option gets repetitive. Option has methods for the common shapes.
| Method | What it does | Result for `Some(x)` | Result for `None` |
|---|---|---|---|
| `map(f)` | Transforms the inner value | `Some(f(x))` | `None` |
| `and_then(f)` | Chains a step that itself returns an `Option` | `f(x)` | `None` |
| `filter(p)` | Keeps the value only if the predicate holds | `Some(x)` or `None` | `None` |
| `unwrap_or(d)` | Extracts the value or uses a default | `x` | `d` |
| `unwrap_or_else(f)` | Same, but computes the default lazily | `x` | `f()` |
| `ok_or(e)` | Converts to `Result` | `Ok(x)` | `Err(e)` |
| `is_some()` / `is_none()` | Tests the variant | `true` / `false` | `false` / `true` |
This program uses several of them:
fn find_user(id: u32) -> Option<&'static str> {
match id {
1 => Some("ada"),
2 => Some("grace"),
_ => None,
}
}
fn initial_of(id: u32) -> Option<char> {
let name = find_user(id)?;
name.chars().next()
}
fn main() {
let upper = find_user(1).map(|n| n.to_uppercase());
println!("{:?}", upper);
let initial = find_user(2).and_then(|n| n.chars().next());
println!("{:?}", initial);
let name = find_user(9).unwrap_or("guest");
println!("{name}");
let missing: Result<&str, String> = find_user(9).ok_or("no such user".to_string());
println!("{:?}", missing);
println!("{:?} {:?}", initial_of(1), initial_of(9));
}It prints:
Some("ADA")
Some('g')
guest
Err("no such user")
Some('a') NoneUse map when the closure returns a plain value. Use and_then when the closure returns an Option. With map in the third case you would get Option<Option<char>>.
The ? operator on Option
In initial_of, find_user(id)? means: if the value is Some(name), bind name and continue. If it is None, return None from the whole function immediately. The enclosing function must return an Option. You can't use ? on an Option inside a function that returns Result, and the reverse is also an error. Use ok_or to convert first.
Choosing a handling style
Common errors
Calling unwrap on a value that can be None
unwrap() returns the inner value for Some and panics for None. expect("message") does the same with your message. Both are acceptable in tests, in examples, and where None would mean a bug in your program. They are a poor choice for input from users, files, or the network.
Moving out of a borrowed Option
A frequent error is matching on a field through &self. This fails with error E0507, "cannot move out of self.nickname which is behind a shared reference":
// Does not compile:
// fn nickname_len(&self) -> usize {
// match self.nickname {
// Some(n) => n.len(),
// None => 0,
// }
// }The pattern Some(n) would move the String out of the struct. Match on a reference instead, or use an adapter:
struct Profile {
nickname: Option<String>,
}
impl Profile {
fn nickname_len(&self) -> usize {
match &self.nickname {
Some(n) => n.len(),
None => 0,
}
}
fn nickname_ref(&self) -> Option<&str> {
self.nickname.as_deref()
}
fn clear(&mut self) -> Option<String> {
self.nickname.take()
}
}
fn main() {
let mut p = Profile { nickname: Some("ace".to_string()) };
println!("{}", p.nickname_len());
println!("{:?}", p.nickname_ref());
println!("{:?}", p.clear());
println!("{:?}", p.nickname_ref());
}The output is 3, Some("ace"), Some("ace"), and None.
match &self.nicknamemakesna&String. Nothing moves.as_ref()turns&Option<T>intoOption<&T>.as_deref()goes one step further and turnsOption<String>intoOption<&str>.take()replaces the value in place withNoneand returns the old one. It works through&mut, and it is the standard way to move a value out of a field you only borrow.
Confusing Option<&T> with &Option<T>
These are different types. &Option<T> is a reference to the whole option. Option<&T> is an option holding a reference. Methods like Vec::first return Option<&T>. If you need an owned value, copied() works for Copy types and cloned() works for Clone types.
Forgetting that Some(0) is still Some
Some(0), Some(""), and Some(false) all count as present. Presence and truthiness are separate. Test with is_some() or a pattern, not by comparing the inner value.
Nested options
Option<Option<T>> has three states: None, Some(None), and Some(Some(x)). It is legal and sometimes meaningful. For example, a map lookup can return Some(None) when the key exists but its stored value is empty. When it appears by accident, flatten() collapses it, or you should switch from map to and_then.
Summary of when to use Option
Use Option when absence is a normal, expected outcome and there is nothing more to say about why. If the caller needs to know why something failed, use Result, which the later chapter on Result and ? covers. Convert between the two with ok_or and .ok().
Exercise
Write a function middle_initial(full: &str) -> Option<char> that returns the first character of the second word in a string such as "Ada Byron Lovelace". It should return None when there is only one word. Use split_whitespace, nth, and ? or and_then. What does it return for "Ada Lovelace", and what for "Ada"?
Show answer
One solution is fn middle_initial(full: &str) -> Option<char> { let word = full.split_whitespace().nth(1)?; word.chars().next() }. For "Ada Lovelace" the second word is "Lovelace", so it returns Some('L'). For "Ada", nth(1) returns None, the ? returns None early, and the result is None. The same function can be written as full.split_whitespace().nth(1).and_then(|w| w.chars().next()).
Exercise
Why does match self.nickname { Some(n) => n.len(), None => 0 } fail inside a &self method when nickname is an Option<String>, and what are two ways to fix it?
Show answer
The pattern Some(n) binds n by value, which would move the String out of a struct that is only borrowed, so the compiler rejects it with E0507. Two fixes are to match on a reference, match &self.nickname { Some(n) => n.len(), None => 0 }, or to use an adapter such as self.nickname.as_ref().map(|n| n.len()).unwrap_or(0).