Sub topic 7
Using ? with Option
This chapter assumes you know Option<T> and match, and have used ? on Result. If not, review the earlier chapters on those topics first.
The same operator, a different early return
Option<T> is either Some(value) or None. A function that may have no answer returns an Option. The ? operator works on it the way it works on Result. If the value is Some, ? unwraps it. If the value is None, ? returns None from the enclosing function right away.
fn first_char_upper(s: &str) -> Option<char> {
let c = s.chars().next()?;
Some(c.to_ascii_uppercase())
}
fn main() {
println!("{:?}", first_char_upper("rust"));
println!("{:?}", first_char_upper(""));
}This prints Some('R') and then None. An empty string has no first character, so next() returns None. The ? then ends the function with None.
What it expands to
The ? operator is shorthand for a match with an early return:
fn first_char_upper_manual(s: &str) -> Option<char> {
let c = match s.chars().next() {
Some(v) => v,
None => return None,
};
Some(c.to_ascii_uppercase())
}Both functions behave the same. The ? version keeps the success path in a straight line.
Chaining lookups
? helps most when several steps can each fail. Each step either produces a value or ends the function:
use std::collections::HashMap;
fn population(
data: &HashMap<&str, HashMap<&str, u32>>,
country: &str,
city: &str,
) -> Option<u32> {
let cities = data.get(country)?;
let pop = cities.get(city)?;
Some(*pop)
}
fn main() {
let mut france = HashMap::new();
france.insert("Paris", 2_100_000);
let mut data = HashMap::new();
data.insert("France", france);
println!("{:?}", population(&data, "France", "Paris"));
println!("{:?}", population(&data, "France", "Lyon"));
println!("{:?}", population(&data, "Spain", "Madrid"));
}The output is Some(2100000), None, None. The function does not say which lookup failed. An Option carries no reason for the absence. If callers need a reason, use a Result instead.
You can also use ? in the middle of an expression:
fn second_word_len(s: &str) -> Option<usize> {
Some(s.split_whitespace().nth(1)?.len())
}Limits to remember
- The return type must match.
?on anOptiononly works in a function that returnsOption. The function body cannot use?onNoneand return something else. OptionandResultdo not mix automatically.Fromconversion applies to error types inside aResult. It does not turn aNoneinto anErr.
Here is a common mistake:
fn first_digit(s: &str) -> Result<char, String> {
let c = s.chars().next()?; // does not compile
Ok(c)
}The compiler reports:
error[E0277]: the `?` operator can only be used on `Result`s, not `Option`s, in a function that returns `Result`The compiler is pointing at the mismatch between the Option on the left and the Result return type. Convert the Option to a Result first, with ok_or. The next chapter covers it in detail:
fn first_digit(s: &str) -> Result<char, String> {
let c = s.chars().next().ok_or("empty input".to_string())?;
Ok(c)
}The reverse mistake gives a matching error. Using ? on a Result in a function that returns Option fails to compile. There, .ok() turns a Result into an Option.
Exercise
Write fn third_char(s: &str) -> Option<char> that returns the third character of s, or None if s has fewer than three characters. Use ? at least once. What does third_char("ab") return?
Show answer
One solution is fn third_char(s: &str) -> Option<char> { let c = s.chars().nth(2)?; Some(c) }. The nth(2) call returns None when there is no third character, and ? returns that None from the function. So third_char("ab") returns None.