The ? operator
Picture yourself as an assistant. Your boss asked you to collect a parcel and make a gift out of it. If the courier brought the parcel, you carry on. If it is a note, you do not deal with it yourself; you hand it straight to your boss and let them decide.
In a program, a function that itself calls functions returning Result acts the same way. So far you only know how to handle each call with match:
use std::num::ParseIntError;
fn plus_one(s: &str) -> Result<i32, ParseIntError> {
let n: i32 = match s.parse() {
Ok(n) => n,
Err(e) => return Err(e),
};
Ok(n + 1)
}
fn main() {
println!("{:?}", plus_one("9")); // Ok(10)
println!("{:?}", plus_one("x")); // Err(ParseIntError { kind: InvalidDigit })
}Let's walk through the example line by line:
use std::num::ParseIntError;makes the name of the parse error type available so you can write it in the signature.- The arm
Ok(n) => ngives the number, and it becomes the value of the wholematch. - The arm
Err(e) => return Err(e)leaves the function and hands the error to whoever called it. Ok(n + 1)returns the result if parsing succeeded.
Four lines for a single parse. With three parses, the function is almost nothing but identical match blocks.
How ? works
The ? operator after an expression with a Result does exactly what that match does:
- if it is
Ok(v), the expression givesv, and the function carries on; - if it is
Err(e), the function returnsErr(e)at once.
The same function with ?:
fn plus_one(s: &str) -> Result<i32, ParseIntError> {
let n: i32 = s.parse()?;
Ok(n + 1)
}
println!("{:?}", plus_one("x")); // Err(ParseIntError { kind: InvalidDigit })The key part is what happens on Err: the function ends right on the line with ?, and nothing below it runs. Step through the program and watch which lines of quarter run on the second call and which are skipped. In the program below, n % 2 is the remainder of division by 2: for an odd number it is 1.
1fn half(n: i32) -> Result<i32, String> {2 if n % 2 == 1 {3 return Err(format!("{n} is odd"));4 }5 Ok(n / 2)6}7 8fn quarter(n: i32) -> Result<i32, String> {9 let h = half(n)?;10 println!("half = {h}");11 let q = half(h)?;12 println!("quarter = {q}");13 Ok(q)14}15 16fn main() {17 println!("{:?}", quarter(12));18 println!("{:?}", quarter(6));19}
main calls quarter(12) and waits for its Result.
On the second call, quarter managed to print only half = 3. On the line let q = half(h)?; the ? operator got an Err and returned it from quarter, so neither println!("quarter = {q}") nor Ok(q) ran. The note that reached main is the very one half wrote.
Here the assistant analogy falls short. The note does not go straight to main; it goes exactly one level up, to the function that called the current one. There it can be handled with match or passed further up with that function's own ?.
Interviewers like to ask this: "What does the ? operator do?" On Ok it takes the value out, and on Err it returns the error from the current function. It does not handle the error itself and, unlike unwrap, it does not panic.
Common mistake
? is used in a plain main:
use std::num::ParseIntError;
fn plus_one(s: &str) -> Result<i32, ParseIntError> {
let n: i32 = s.parse()?;
Ok(n + 1)
}
fn main() {
let n = plus_one("9")?; // ✗
println!("{n}");
}error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)The program does not compile. On Err, the ? operator needs somewhere to return the error, but this main returns (), which cannot hold one. It does not matter that "9" parses fine: the return type is checked at build time, before anything runs. In a function that returns Option, ? works too: on None it returns None at once.
The fix is to change the return type of main:
use std::num::ParseIntError;
fn plus_one(s: &str) -> Result<i32, ParseIntError> {
let n: i32 = s.parse()?;
Ok(n + 1)
}
fn main() -> Result<(), ParseIntError> {
let n = plus_one("9")?;
println!("{n}"); // 10
let m = plus_one("x")?;
println!("{m}");
Ok(())
}-> Result<(), ParseIntError>letsmainreturn a parse error.plus_one("9")?gives10, and the program prints it.plus_one("x")?gets anErrand returns it frommain:println!("{m}")does not run.Ok(())at the end means "everything went fine, and there is no result".
When main returns an Err, the program prints Error: ParseIntError { kind: InvalidDigit } and exits with code 1.
Key points
?after aResulttakes the value out ofOk, and onErrreturns the error from the current function at once.- On an error, the lines below
?do not run; the error goes to the calling function, not into a panic. ?works only in a function that returnsResultorOption; in a plainmainit is error E0277.maincan returnResult<(), E>, and then you can use?in it too.