Sub topic 5
What the compiler does with ?
This chapter assumes you can read match expressions, know what Result<T, E> and Option<T> are, and have used ? in at least one function. It takes the operator apart so you can predict what it does, and why some uses fail to compile.
The short version
expr? unwraps a success value or returns early from the enclosing function. Conceptually, it is a match on expr:
- If the value is
Ok(v)orSome(v), the wholeexpr?expression evaluates tov, and execution continues. - If the value is
Err(e)orNone, the function returns immediately. ForErr(e), the error is first passed throughFrom::from.
Two parts of that description cause most of the confusion, so the rest of the chapter is about them: the early return, and the From call.
Writing the expansion by hand
The two functions below behave the same. The first uses ?. The second spells out what ? does for a Result.
use std::num::ParseIntError;
fn double_short(s: &str) -> Result<i32, ParseIntError> {
let n = s.trim().parse::<i32>()?;
Ok(n * 2)
}
fn double_long(s: &str) -> Result<i32, ParseIntError> {
let n = match s.trim().parse::<i32>() {
Ok(v) => v,
Err(e) => return Err(From::from(e)),
};
Ok(n * 2)
}
fn main() {
println!("{:?}", double_short(" 21 "));
println!("{:?}", double_long("x"));
}Running it prints:
Ok(42)
Err(ParseIntError { kind: InvalidDigit })In double_long, the Ok(v) => v arm is why ? can sit in the middle of an expression. The match produces a value, so let n = ... receives the unwrapped integer. The Err arm has type ! (it never produces a value, because it returns), so it fits next to the Ok arm without a type mismatch.
The control flow
The diagram shows the path ? takes for a Result.
The real mechanism: the Try trait
The match above is a faithful model for Result and Option, but the compiler does not special-case those two types. Since Rust 1.55 the operator is defined in terms of two traits in std::ops: Try and FromResidual. Both are unstable to implement yourself, but you can see them in compiler messages.
The idea is this:
Try::branchtakes the value and returns aControlFlow. It is eitherContinue(output), the success value, orBreak(residual), the "everything except the success value".- On
Continue(output), the?expression evaluates tooutput. - On
Break(residual), the compiler emitsreturn FromResidual::from_residual(residual).
The residual for Result<T, E> is Result<Infallible, E>. The FromResidual implementation for the function's return type is where the From call lives. For Result<T, F>, it builds Err(From::from(e)). For Option<T>, there is no error value to convert, so it simply builds None.
This design has a practical consequence. The return type of the enclosing function decides what ? is allowed to do. The type of the expression before the ? only supplies the residual.
| Aspect | `?` on `Result<T, E>` | `?` on `Option<T>` |
|---|---|---|
| Success case | Evaluates to the `T` inside `Ok` | Evaluates to the `T` inside `Some` |
| Failure case | Returns `Err(From::from(e))` | Returns `None` |
| Enclosing function must return | `Result<_, F>` where `F: From<E>` | `Option<_>` |
| Error conversion | Yes, through `From` | None, there is no error value |
The From call is always there
The From::from(e) call appears even when the error types are identical. That works because the standard library has a blanket implementation, impl<T> From<T> for T, which returns the value unchanged. So in double_short, the conversion is a no-op that the optimizer removes.
When the types differ, From does the real work. Here is a function whose error type is a custom enum, with the expansion written out:
use std::num::ParseIntError;
#[derive(Debug)]
enum AppError {
Parse(ParseIntError),
}
impl From<ParseIntError> for AppError {
fn from(e: ParseIntError) -> Self {
AppError::Parse(e)
}
}
fn with_question_mark(s: &str) -> Result<i32, AppError> {
let n = s.parse::<i32>()?;
Ok(n)
}
fn written_out(s: &str) -> Result<i32, AppError> {
let n = match s.parse::<i32>() {
Ok(v) => v,
Err(e) => return Err(AppError::from(e)),
};
Ok(n)
}
fn main() {
println!("{:?}", with_question_mark("12"));
println!("{:?}", with_question_mark("twelve"));
println!("{:?}", written_out("twelve"));
}The output is:
Ok(12)
Err(Parse(ParseIntError { kind: InvalidDigit }))
Err(Parse(ParseIntError { kind: InvalidDigit }))The compiler picks the From implementation by looking at the function's declared error type. That is why you annotate return types on functions, and on closures that use ?.
Only the error is converted
From applies to the Err payload only. The Ok type must already match what the function declares, and you convert it yourself. ? also never converts between Option and Result. That takes ok_or, ok_or_else, or ok(), covered in the chapter on moving between the two types.
Conversions from string slices
Because the standard library implements From<&str> for Box<dyn Error>, you can use ? on a plain Err of a string slice when the function returns that boxed type:
use std::error::Error;
fn check(n: i32) -> Result<i32, Box<dyn Error>> {
if n < 0 {
Err("negative input")?;
}
Ok(n)
}
fn main() {
println!("{:?}", check(5));
match check(-1) {
Ok(_) => {}
Err(e) => println!("error: {e}"),
}
}This prints Ok(5) and then error: negative input. It works through the same From call. Most code writes return Err("negative input".into()) instead, which reads better.
Which function does the return leave?
? expands to a return, so it leaves the innermost enclosing function or closure, not the enclosing block or loop. In a closure, ? returns from the closure only:
use std::num::ParseIntError;
fn main() {
let add_one = |s: &str| -> Result<i32, ParseIntError> {
let n = s.parse::<i32>()?;
Ok(n + 1)
};
println!("{:?}", add_one("41"));
println!("{:?}", add_one("oops"));
println!("main keeps running");
}The closure's return type is annotated because the compiler cannot otherwise work out which From target to use. A closure's inferred return type is fixed by its body, and a bare ? leaves the error type ambiguous. Without the annotation you usually get error E0282 ("type annotations needed").
Inside a loop, ? exits the whole function, not just the iteration. If you want to skip failures and keep looping, use match, if let Ok(..), or .filter_map(Result::ok) instead.
Reading the compiler errors
Most ? errors fall into three shapes. Each one maps directly onto the expansion.
The function returns the wrong kind of type
If the function returns (), there is no FromResidual implementation to call:
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)The usual fix is to change the function's return type to Result<(), E> and end it with Ok(()). In main, the fix is to return a Result, which a later chapter covers.
Option and Result are mixed
Using ? on an Option in a function that returns Result fails, and so does the reverse. The message says the operator "can only be used on Results, not Options, in a function that returns Result" (or the mirror image). Convert first, for example with .ok_or("missing")?.
No From implementation exists
This is the error from the earlier expansion:
error[E0277]: `?` couldn't convert the error to `String`The note under it says that From<ParseIntError> is not implemented for String. Either implement From for your error type, or convert explicitly with map_err. For example, .map_err(|e| e.to_string())? turns the error into a String before ? runs.
Quick checks when `?` misbehaves
- Look at the function's declared return type. That is the type
?converts into. - Check whether
From<SourceError> for TargetErrorexists. The source is theEin the expression before?. - Check that the
OkorSomeside needs no conversion. - Check whether you are inside a closure, because that is where
?returns to.
Exercise
Rewrite this function without ?, using only match and return: fn len_of_first(s: &str) -> Option<usize> { let w = s.split_whitespace().next()?; Some(w.len()) }
Show answer
Replace the first line with let w = match s.split_whitespace().next() { Some(v) => v, None => return None }; and keep Some(w.len()) as the last line. For Option, the failure arm returns None directly, and no From call is involved.
Exercise
This function does not compile: fn parse(s: &str) -> Result<i32, String> { let n = s.parse::<i32>()?; Ok(n) }. Explain which part of the expansion fails, and give two fixes.
Show answer
The failure arm calls From::from(e) to convert ParseIntError into String, but String does not implement From<ParseIntError>, so the ? cannot convert the error. Fix 1: convert explicitly with s.parse::<i32>().map_err(|e| e.to_string())?. Fix 2: change the return type to a custom error type, or Box<dyn Error>, that does implement From<ParseIntError>.
Exercise
A closure containing ? sits inside main, which returns (). Does the ? make main fail to compile? Explain.
Show answer
No. ? returns from the innermost enclosing function or closure, so it needs the closure to return a Result or Option (annotate the closure's return type so inference can pick the error type). main is not involved, and it continues after the closure returns.