Sub topic 9
Propagating errors with the ? operator
This chapter assumes you can write match on Option and Result, and that you know the basic combinators from earlier chapters. You should also be comfortable with function return types and with the idea that a trait such as From converts one type into another.
The problem: repeated early returns
Most fallible functions call other fallible functions. If any step fails, the usual response is to stop and hand the error to the caller. Written with match, that looks like this:
use std::num::ParseIntError;
fn parse_pair(a: &str, b: &str) -> Result<(i32, i32), ParseIntError> {
let x = match a.trim().parse::<i32>() {
Ok(v) => v,
Err(e) => return Err(e),
};
let y = match b.trim().parse::<i32>() {
Ok(v) => v,
Err(e) => return Err(e),
};
Ok((x, y))
}
fn main() {
println!("{:?}", parse_pair("3", " 4 "));
println!("{:?}", parse_pair("3", "four"));
}Four of the ten lines in parse_pair only forward an error. The ? operator replaces that pattern.
How ? works on Result
Place ? after an expression of type Result<T, E>. If the value is Ok(v), the whole expression evaluates to v. If it is Err(e), the enclosing function returns immediately with Err(e).
use std::num::ParseIntError;
fn parse_pair(a: &str, b: &str) -> Result<(i32, i32), ParseIntError> {
let x = a.trim().parse::<i32>()?;
let y = b.trim().parse::<i32>()?;
Ok((x, y))
}
fn main() {
println!("{:?}", parse_pair("3", " 4 "));
println!("{:?}", parse_pair("3", "four"));
}This prints Ok((3, 4)) and then Err(ParseIntError { kind: InvalidDigit }). The success path now reads top to bottom with no nesting.
What the compiler does
expr? behaves roughly like this:
match expr {
Ok(v) => v,
Err(e) => return Err(From::from(e)),
}The real implementation goes through the Try machinery, but this model predicts the behavior. Two consequences follow from it.
?returns from the function that contains it, not from the current block or loop.- The error passes through
From::from. When the error types are identical, that call does nothing. When they differ, aFromimplementation must exist. The chapter on error conversion covers this in detail.
Because return runs destructors for local variables, values such as open files or locks are released as usual on the early-exit path.
Using ? on Option
? also works on Option<T>. Some(v) yields v. None makes the function return None.
fn first_char_upper(words: &[&str]) -> Option<char> {
let first = words.first()?;
let c = first.chars().next()?;
Some(c.to_ascii_uppercase())
}
fn main() {
println!("{:?}", first_char_upper(&["rust", "go"]));
println!("{:?}", first_char_upper(&[]));
println!("{:?}", first_char_upper(&[""]));
}This prints Some('R'), None, and None. Each ? is a point where the function can stop. An empty slice and an empty string both end in None, and the caller cannot tell them apart. If the caller needs to know which step failed, return a Result instead.
The return type must match
? can only be used in a function whose return type can absorb the early return. The rules are:
| Operand | Function must return | On failure the function returns |
|---|---|---|
| `Result<T, E>` | `Result<U, F>` where `F: From<E>` | `Err(F::from(e))` |
| `Option<T>` | `Option<U>` | `None` |
The compiler does not convert between the two families. Using ? on an Option inside a function that returns Result is an error, and so is the reverse. Convert explicitly first, using ok_or or ok_or_else for Option to Result and .ok() for Result to Option:
fn port_from_args(args: &[String]) -> Result<u16, String> {
let raw = args.get(1).ok_or("missing port argument")?;
let port = raw
.parse::<u16>()
.map_err(|e| format!("bad port {raw}: {e}"))?;
Ok(port)
}
fn main() {
let none: Vec<String> = vec![String::from("app")];
let bad = vec![String::from("app"), String::from("x1")];
let good = vec![String::from("app"), String::from("8080")];
println!("{:?}", port_from_args(&none));
println!("{:?}", port_from_args(&bad));
println!("{:?}", port_from_args(&good));
}The first ? receives Result<&String, &str>. The function's error type is String, and the standard library provides From<&str> for String, so the conversion happens silently. The second ? follows map_err, which already produced a String, so no conversion is needed.
Common compile errors
The three mistakes below are the ones you will meet most often.
?in a function that returns(). This happens most often inmainand in test helpers. The compiler reports that?can only be used in a function that returnsResultorOption. Change the return type, or handle the value withmatch. Chapter material onmainreturningResultshows the usual fix.- Mixing
OptionandResult. See the table above. Convert withok_orbefore applying?. - No
Fromconversion between error types. If a function returnsResult<u16, String>and applies?to aParseIntError, compilation fails with a message thatFrom<ParseIntError>is not implemented forString. Fix it withmap_err, or define an error type that implementsFrom.
? inside closures
A closure is a separate function body, so ? inside a closure returns from the closure, not from the surrounding function. The closure's own return type must therefore be a Result or Option. Annotate it if inference fails:
use std::num::ParseIntError;
fn main() {
let double = |s: &str| -> Result<i32, ParseIntError> {
let n = s.trim().parse::<i32>()?;
Ok(n.saturating_mul(2))
};
println!("{:?}", double("21"));
println!("{:?}", double("?"));
}Using ? in chains
? binds tighter than most operators and fits at the end of a method call. You can apply it several times in one expression:
fn digit_sum(s: &str) -> Result<u32, std::num::ParseIntError> {
let n = s.trim().parse::<u32>()?;
Ok(n.to_string().chars().filter_map(|c| c.to_digit(10)).sum())
}
fn main() {
println!("{:?}", digit_sum("1234"));
println!("{:?}", digit_sum("-5"));
}When a value is an Option<Result<T, E>>, ? does not unwrap both layers. Call .transpose() to get a Result<Option<T>, E> and then apply ?.
When not to use ?
Do not use ? where the function can recover from the failure. If a missing setting has a sensible default, unwrap_or or unwrap_or_else expresses that more clearly than propagating and handling the error elsewhere. Propagate when the caller is better placed to decide what to do.
Exercise
The function below fails to compile. Explain why, and rewrite the body so it returns Err("empty input".tostring()) for an empty slice and otherwise the parsed value of the first element. fn firstnumber(items: &[&str]) -> Result<i32, String> { let first = items.first()?; first.parse::<i32>() }
Show answer
There are two problems. First, items.first() returns an Option, and ? on an Option is not allowed in a function that returns Result. Second, parse::<i32>() returns Result<i32, ParseIntError>, but the function's error type is String, and there is no From<ParseIntError> for String. A working version is:
fn firstnumber(items: &[&str]) -> Result<i32, String> {
let first = items.first().okor("empty input".tostring())?;
first.parse::<i32>().maperr(|e| e.tostring())
}
okor converts the Option into a Result so ? applies, and map_err converts the parse error into a String.