Sub topic 7
Using ? with Option
This chapter assumes you know how Result and Option work, how match works, and how ? behaves on a Result inside a function that returns Result. Here you will apply the same operator to Option, see where it differs, and learn the cases where the compiler rejects it.
Why ? works on Option
An Option<T> is either Some(value) or None. A None is not an error in the sense of carrying a reason. It means a value is absent: a missing map key, an empty iterator, a failed split_once. Code that looks things up one after another needs the same early-exit pattern as code that handles errors: if a step has no value, stop and report that.
Without ?, that code turns into nested match expressions. With ?, each step is one line.
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. When s.chars().next() is Some(c), the expression ...? evaluates to c. When it is None, the function returns None immediately.
What the compiler does with ? on Option
For Option, ? is the same shape as for Result, with one part removed. The manual form is:
fn first_char_upper_manual(s: &str) -> Option<char> {
let c = match s.chars().next() {
Some(c) => c,
None => return None,
};
Some(c.to_ascii_uppercase())
}
fn main() {
println!("{:?}", first_char_upper_manual("rust"));
println!("{:?}", first_char_upper_manual(""));
}With Result, the Err arm passes its payload through From::from, which is how error types get converted. A None has no payload, so there is nothing to convert. The None is returned as is.
Internally the compiler does not generate this match literally. It calls the Try and FromResidual traits, which is why ? also works on other types. For everyday code, the match above is the right mental model.
Chaining lookups
The strongest use of ? on Option is a chain of dependent lookups. This example walks through a map, then an optional address, then an optional city.
use std::collections::HashMap;
struct Address {
city: Option<String>,
}
struct User {
address: Option<Address>,
}
fn city_of(users: &HashMap<u32, User>, id: u32) -> Option<&str> {
let user = users.get(&id)?;
let address = user.address.as_ref()?;
let city = address.city.as_deref()?;
Some(city)
}
fn main() {
let mut users = HashMap::new();
users.insert(
1,
User {
address: Some(Address {
city: Some("Lisbon".to_string()),
}),
},
);
users.insert(2, User { address: None });
println!("{:?}", city_of(&users, 1));
println!("{:?}", city_of(&users, 2));
println!("{:?}", city_of(&users, 3));
}The output is Some("Lisbon"), None, None. The function cannot tell you which step failed, and that is the trade-off with Option. If the caller needs to know why, use Result instead (see the conversion section below).
Two details in this code matter:
as_ref()turns&Option<Address>intoOption<&Address>. Without it,?would try to move theAddressout of a borrowedUser, and the compiler would reject that.as_deref()turns&Option<String>intoOption<&str>. The returned&strborrows fromusers, which is why the signature returnsOption<&str>with the lifetime tied to the map.
Mixing ? with method chains
You can use ? in the middle of a method chain, because it is a postfix operator.
fn parse_pair(line: &str) -> Option<(&str, i32)> {
let (key, value) = line.split_once('=')?;
let n = value.trim().parse::<i32>().ok()?;
Some((key.trim(), n))
}
fn main() {
println!("{:?}", parse_pair("width = 40"));
println!("{:?}", parse_pair("width"));
println!("{:?}", parse_pair("width = wide"));
}This prints Some(("width", 40)), None, None. The call .ok() converts a Result<i32, ParseIntError> into an Option<i32>, discarding the error. It is the standard bridge when a function returns Option but one step produces a Result. Use it only when you really do not care why the parse failed.
Closures and other return contexts
The ? operator returns from the nearest enclosing function or closure, not from the enclosing statement. A closure that returns Option can use ? inside its own body.
fn main() {
let sum = (|| {
let a = "4".parse::<i32>().ok()?;
let b = "5".parse::<i32>().ok()?;
Some(a + b)
})();
println!("{:?}", sum);
}This prints Some(9). The closure's return type is inferred as Option<i32> from the Some(a + b) at the end. If you want this effect without defining a named function, an immediately called closure is the stable way to get it. Rust has an unstable try block feature for the same purpose, but it is not available on the stable compiler.
Rules and limits
The rules are short.
| Situation | Allowed? | Why |
|---|---|---|
| `?` on `Option` in a function returning `Option<U>` | Yes | `None` converts directly to the return type. `U` can differ from `T`. |
| `?` on `Option` in a function returning `Result` | No | There is no way to build an `Err` from a bare `None`. |
| `?` on `Result` in a function returning `Option` | No | There is no rule for turning an error into `None`. |
| `?` on `Option` in `main` returning `()` | No | `()` cannot represent an early return. |
The two mismatch rows are the common source of compiler errors. This function fails to compile:
fn first_word_len(s: &str) -> Result<usize, String> {
let word = s.split_whitespace().next()?; // does not compile
Ok(word.len())
}The compiler reports error E0277, saying the ? operator can only be used on Results in a function that returns Result, and that the operand here is an Option. The exact wording changes between compiler versions, but the shape is always that the operand type and the return type must be in the same family.
Converting so ? works
To use an Option inside a Result function, attach an error with ok_or or ok_or_else:
fn first_word_len(s: &str) -> Result<usize, String> {
let word = s
.split_whitespace()
.next()
.ok_or("input has no words")?;
Ok(word.len())
}
fn port_from(s: Option<&str>) -> Result<u16, String> {
let text = s.ok_or("missing port")?;
let port = text.parse::<u16>().map_err(|e| e.to_string())?;
Ok(port)
}
fn main() {
println!("{:?}", first_word_len("hello world"));
println!("{:?}", first_word_len(" "));
println!("{:?}", port_from(Some("8080")));
println!("{:?}", port_from(None));
println!("{:?}", port_from(Some("eighty")));
}In first_word_len, ok_or("input has no words") produces a Result<&str, &str>. The ? then converts the &str error into the function's String error using From<&str> for String. This is the same From conversion you saw for Result. The next chapter covers ok_or, ok_or_else, and map_err in more detail.
Going the other way, use .ok() to turn a Result into an Option, as in parse_pair above.
Common mistakes
- Using
?on a reference lookup and then trying to return an owned value.map.get(key)?gives you a&V. Call.clone(),.to_string(), or change the return type to hold a reference. - Expecting
?to treatSome(false)orSome(0)as a failure. OnlyNonetriggers the early return. The contents ofSomeare never inspected. - Discarding useful errors with
.ok()?when a caller would benefit from them. If you find yourself writing.ok()?on most lines, the function probably should returnResult. - Forgetting that a
Nonereturned by?carries no location. When several steps in a chain can fail, debugging theNonemeans checking each step separately.
Exercise
Write a function ends_sum(values: &[i32]) -> Option<i32> that returns the sum of the first and last elements, using ? on first() and last(). What does it return for an empty slice, and why does the function still compile when the two elements are both references?
Show answer
The body is let a = values.first()?; let b = values.last()?; Some(a + b). For an empty slice, first() returns None, so ? returns None immediately. It compiles with references because &i32 + &i32 is implemented in the standard library and produces an i32, so Some(a + b) has type Option<i32>. For &[3, 4, 5] the result is Some(8), and for a single-element slice such as &[7] the first and last element are the same, so the result is Some(14).