Sub topic 2
Option<T>: a value that may be missing
This chapter assumes you know basic Rust syntax, enums and match, ownership and borrowing, and have a conceptual grasp of generics. Here you will see how Option<T> is defined, how to write functions that return it, and the mistakes people commonly make when first using it.
The definition
Option<T> is an ordinary enum in the standard library:
enum Option<T> {
None,
Some(T),
}Some(value) holds a value of type T. None means there is no value. Both variants are in the prelude, so you write Some and None without importing anything.
Because Option<i32> and i32 are different types, you cannot use an Option<i32> as if it were an i32. The compiler rejects the code until you decide what happens in the None case. This is how Rust removes null pointer errors: a value that can be missing says so in its type, and a value that cannot be missing has no Option around it.
Returning an Option
Use Option<T> when a function has exactly one reason it might not produce a value, and the caller does not need an explanation. Searching a slice is the typical case.
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"),
}
}find itself returns an Option, so the function passes it straight through. The copied call turns the iterator's &i32 items into i32 values. In main, match must cover both variants. If you delete the None arm, the program no longer compiles.
Common errors
- Using the Option as the inner value. Writing
first_even(&v) + 1fails with a type mismatch, becauseOption<i32>does not implement addition with an integer. Extract the value first. - Using
Optionwhen the caller needs a reason.Nonecarries no information. If callers must distinguish "not found" from "input was invalid", return aResultinstead. The next chapter covers it. - Nesting by accident.
Option<Option<T>>is legal but usually means a step returned anOptionwhere you wanted to flatten it. Check which call produced the extra layer. - Forgetting the type for
None.let x = None;fails because the compiler cannot inferT. Writelet x: Option<i32> = None;or usexin a way that fixes the type.
Where this leads
Matching on every Option gets verbose. Later chapters introduce if let, let else, and methods such as map and unwrap_or that handle common cases in one line.
Exercise
Why does let n: i32 = first_even(&[2, 4]); fail to compile, and what is the smallest change that makes the types agree if you are certain a value exists?
Show answer
The function returns Option<i32>, and Option<i32> is a different type from i32. The compiler will not convert one to the other implicitly. If you are certain a value exists, you can change the annotation to Option<i32> and handle it with match, or call .unwrap() to extract the value. unwrap panics on None, so use it only when the None case is truly impossible.
Exercise
Write a function last_char(s: &str) -> Option<char> that returns the final character of a string, and say what it returns for an empty string.
Show answer
fn last_char(s: &str) -> Option<char> { s.chars().last() }. For an empty string there is no final character, so chars().last() returns None.