Rust Reference ยท Operators and Expressions
The ? operator
Reference for the Rust ? operator: early return for Result and Option, automatic From conversion of errors, where it can be used and common mistakes.
The ? operator is a postfix operator that unwraps a success value or returns early from the enclosing function. Applied to a Result<T, E>, it yields the Ok value, or returns Err(From::from(e)) from the function. Applied to an Option<T>, it yields the Some value or returns None.
It replaces the long match that every fallible call would otherwise need, so a chain like read()?.parse()? reads top to bottom with the error handling out of the way. The function you use it in must return a type that can absorb the failure: Result, Option, or another type that implements the (still unstable) Try trait, such as Poll.
fn double(text: &str) -> Result<i32, std::num::ParseIntError> { let n: i32 = text.trim().parse()?; Ok(n * 2) }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
expr? // for Result<T, E> in a function returning Result<U, F> where F: From<E>: match expr { Ok(v) => v, Err(e) => return Err(From::from(e)), } // for Option<T> in a function returning Option<U>: match expr { Some(v) => v, None => return None, }
| Part | Description |
|---|---|
expr |
A Result or Option value (or any type implementing Try). |
| Enclosing function | Must return a compatible type: Result<_, F> with F: From<E>, or Option<_>. |
Returns: the unwrapped T on success; otherwise the enclosing function returns.
Edge cases: ? can also be used in closures that return Result/Option, in async blocks, and in main if main returns Result<(), E> where E: Debug (a returned Err makes the process exit with code 1 and prints Error: ... to stderr).
Usage notes
- Mixing Option and Result does not compile.
?on anOptioninside a function returningResultis an error. Convert first:opt.ok_or(MyError::Missing)?oropt.ok_or_else(|| ...)?. In the other direction,res.ok()?turns an error intoNone. - Error conversion: the
Fromcall is whyBox<dyn Error>andanyhow-style types accept almost any error. With a concrete error enum you write oneimpl From<X>per source error (or derive it with a crate such asthiserror). - Context is lost:
?forwards the error unchanged. Usemap_err(|e| ...)when you need to add what you were doing. - Early return, not a panic: values on the stack are dropped normally as the function returns, so guards and destructors run.
- Type inference:
let n = s.parse()?;needs a type somewhere (let n: i32,parse::<i32>()), because the target of the parse is not implied by the?. - Blocks and loops:
?returns from the whole function (or closure), not from the surrounding block. Wrap code in a closure or an inner function if you want to catch a failure locally.tryblocks are unstable. - Not for
mainreturning(): the compiler reports that the?operator can only be used in a function that returnsResultorOption. - Style: prefer
?overunwrap()in anything that is not a quick test; reserveunwrapandexpectfor states you can prove impossible.