Skip to content
Theory · Errors · lesson 6 of 8

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:

Rust
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:

  1. use std::num::ParseIntError; makes the name of the parse error type available so you can write it in the signature.
  2. The arm Ok(n) => n gives the number, and it becomes the value of the whole match.
  3. The arm Err(e) => return Err(e) leaves the function and hands the error to whoever called it.
  4. 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 gives v, and the function carries on;
  • if it is Err(e), the function returns Err(e) at once.

The same function with ?:

Rust
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.

LiveEarly return with ?step 1 of 13 · frames: 1

main calls quarter(12) and waits for its Result.

Watch where quarter ends when half returns Err

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:

Rust
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}");
}
TEXT
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:

Rust
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(())
}
  1. -> Result<(), ParseIntError> lets main return a parse error.
  2. plus_one("9")? gives 10, and the program prints it.
  3. plus_one("x")? gets an Err and returns it from main: println!("{m}") does not run.
  4. 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 a Result takes the value out of Ok, and on Err returns 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 returns Result or Option; in a plain main it is error E0277.
  • main can return Result<(), E>, and then you can use ? in it too.