Skip to content
Tutorials Center
My learning

Topics

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.

Rust
fn double(text: &str) -> Result<i32, std::num::ParseIntError> {
    let n: i32 = text.trim().parse()?;
    Ok(n * 2)
}

Try it

Rust Result and Option with ?

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.

Rust Error conversion with From and Box dyn Error

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

Rust
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 an Option inside a function returning Result is an error. Convert first: opt.ok_or(MyError::Missing)? or opt.ok_or_else(|| ...)?. In the other direction, res.ok()? turns an error into None.
  • Error conversion: the From call is why Box<dyn Error> and anyhow-style types accept almost any error. With a concrete error enum you write one impl From<X> per source error (or derive it with a crate such as thiserror).
  • Context is lost: ? forwards the error unchanged. Use map_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. try blocks are unstable.
  • Not for main returning (): the compiler reports that the ? operator can only be used in a function that returns Result or Option.
  • Style: prefer ? over unwrap() in anything that is not a quick test; reserve unwrap and expect for states you can prove impossible.