Sub topic 5
What the compiler does with ?
This chapter assumes you can read match expressions and know that Result<T, E> has the variants Ok(T) and Err(E). You should also know that From is a trait for converting one type into another. The goal is to see that ? is shorthand for code you could write yourself.
The expansion
The ? operator is a match with an early return. For a Result, the expression expr? behaves like this:
match expr {
Ok(v) => v,
Err(e) => return Err(From::from(e)),
}If the value is Ok, the whole expression evaluates to the inner value. If it is Err, the function returns immediately. The error passes through From::from on the way out.
Writing it out by hand
Both functions below do the same thing. The first uses ?. The second writes out the expansion.
use std::num::ParseIntError;
fn with_question(s: &str) -> Result<i32, ParseIntError> {
let n = s.trim().parse::<i32>()?;
Ok(n)
}
fn with_match(s: &str) -> Result<i32, ParseIntError> {
let n = match s.trim().parse::<i32>() {
Ok(v) => v,
Err(e) => return Err(From::from(e)),
};
Ok(n)
}
fn main() {
println!("{:?}", with_question(" 42 "));
println!("{:?}", with_match(" 42 "));
println!("{:?}", with_question("x"));
println!("{:?}", with_match("x"));
}The program prints Ok(42) twice, then Err(ParseIntError { kind: InvalidDigit }) twice.
Where the conversion happens
In the example above, the error type is ParseIntError on both sides. The standard library has a blanket implementation, impl<T> From<T> for T, which returns the value unchanged. So when the types match, the conversion costs nothing.
When the function's error type differs from the error you are propagating, the compiler looks for From<SourceError> for TargetError. If it finds one, the conversion is automatic. If it does not, compilation fails. The next chapter covers how to write those implementations.
What `?` returns from
The early return exits the enclosing function, not the enclosing block. This matters in two places:
- Inside a closure,
?returns from the closure. The closure's own return type must support?. - Inside a
looporifblock,?still leaves the whole function.
The expansion also explains the error message you get when the return type is wrong. The expansion contains return Err(...), so the function must return a type that can hold an Err. In a function that returns (), the compiler reports that ? can only be used in a function that returns Result or Option.
Reading the expansion for `Option`
For Option, the expansion has the same shape but no conversion step:
match expr {
Some(v) => v,
None => return None,
}The ? operator does not mix the two types. A Result value used with ? needs a function that returns Result. An Option value needs a function that returns Option. A later chapter shows how to bridge the two.
Summary of the rules
| Expression type | On success | On failure |
|---|---|---|
| `Result<T, E>` | Evaluates to `T` | Returns `Err(From::from(e))` |
| `Option<T>` | Evaluates to `T` | Returns `None` |
Exercise
A function returns Result<i32, String> and contains the line let n = s.parse::<i32>()?;. Why does it fail to compile, and what does the expansion tell you about the cause?
Show answer
The expansion calls From::from on the ParseIntError to produce a String, and the standard library has no impl From<ParseIntError> for String. Without a From implementation between the two error types, the conversion step cannot compile. You can fix it by changing the error type to ParseIntError, by writing .maperr(|e| e.tostring())?, or by defining an error type that implements From<ParseIntError>.