? Operator (Rust)

The ? operator propagates errors concisely: applied to a Result or Option, it unwraps the success value or returns the error/None early from the enclosing function. It replaces verbose match boilerplate.

Rust

Writing value? after an expression that returns Result<T, E> means 'if this is Ok(v), give me v; if it is Err(e), return Err(e) from this function right now'. The same works on Option, returning None early. This turns a 6-line match into a single character.

Because ? returns the error, the enclosing function must itself return a compatible Result or Option. The error types must match or be convertible — ? automatically calls .into() (via the From trait), so a function returning Result<_, Box<dyn Error>> can absorb many error types.

The ? operator is the heart of ergonomic Rust error handling: chain fallible calls (parse, read, open) with ? and let errors bubble up to a caller that decides how to handle them, rather than littering code with unwrap or nested matches.

Syntax

fn run() -> Result<i32, std::num::ParseIntError> {
    let n: i32 = "42".parse()?;
    Ok(n * 2)
}

Examples

Rust

fn double(s: &str) -> Result<i32, std::num::ParseIntError> {
    let n: i32 = s.parse()?; // returns Err early on failure
    Ok(n * 2)
}

fn main() {
    println!("{:?}", double("21"));
    println!("{}", double("x").is_err());
}

Output:

Ok(42)
true

Learn it in a lesson

See also

Back to the Dictionary