`?` operator
? unwraps Ok or Some, or returns early on Err or None. In a Result function it also converts the error type with From.
Detailed Explanation
let file = File::open(path)?; is the common form. If open returns Ok(file), the ? evaluates to file and execution continues. If it returns Err(e), the function returns Err(e.into()) immediately. Destructors still run for values that already went out of scope, the same as an explicit return.
The conversion is the part people miss. ? does not require the inner error to be the same type as the function's E. It requires From<InnerError> for E. That is how a function returning anyhow::Error or your own enum can call File::open, str::parse, and a database crate and still use ? on every line. You write the From impls (or #[from] with thiserror) once.
? also works on Option. In a function that returns Option<T>, let x = maybe?; returns None when maybe is None. There is no From conversion for Option; absence has no extra payload to convert. You cannot use ? on a Result inside a function that returns Option without mapping, or on an Option inside a Result function without ok_or.
The operator is allowed in functions that return Result, Option, Poll, or another type that implements the Try trait. main may return Result<(), E> so you can use ? at the top level. In a function that returns () or i32, ? is a compile error.
? is not a hidden panic. It is a hidden return. That is better than unwrap, and it still changes control flow. A long chain a()?.b()?.c()? is readable when every step fails the same way. It is unreadable when you need to wrap context around one of the errors; then write a().map_err(...)? or use anyhow's .with_context(|| ...).
When you write ?: almost every fallible call in a function that already returns Result or Option. When you write match: you must distinguish error cases here, not above. When you write unwrap: you have proved the failure is a bug.
Code Examples
fn parse_port(raw: &str) -> Result<u16, std::num::ParseIntError> {
let n = raw.parse::<u16>()?;
Ok(n)
}
fn first_even(nums: &[i32]) -> Option<i32> {
let first = nums.first()?;
if first % 2 == 0 { Some(*first) } else { None }
}
fn main() {
println!("{:?}", parse_port("8080")); // prints: Ok(8080)
println!("{:?}", first_even(&[3, 4])); // prints: None
}Common Gotchas
`?` needs a `Try` return type
A function returning `()` cannot use `?`. Change the return type to `Result` or handle the error with `match`.
No automatic `Option` to `Result` conversion
`maybe?` inside `-> Result<T, E>` does not compile. Write `maybe.ok_or(err)?` or `ok_or_else`.
`From` can hide a coarse conversion
If every error becomes `anyhow::Error` or `Box<dyn Error>`, callers cannot match. Convert at the application edge, not in a library's public `?` path, unless that is the API.
`?` in an `async` function awaits nothing
You still write `.await?` when the fallible thing is a future. The order is await, then try.