Skip to the workspace
Pebellslearn by building
Types and Error Handling  ›  Lesson

Propagating Errors with ?

Propagating Errors and `?` Operator 12 minThe ? operator unwraps an Ok or Some value and otherwise returns the error or None from the current function straight away.

rust / Propagating Errors with ?

Explore each scene at your own pace.

01 · The rule

The rule

Propagating Errors with ?

The ? operator unwraps an Ok or Some value and otherwise returns the error or None from the current function straight away.

Follow an early error return through the question-mark operator.

Reading a loan request means several steps that can fail: parse the card number, parse the number of days, look up the book. Writing a full match for each step buries the real logic. Usually the function should just stop and let its caller deal with the problem. Rust has a single character for that.

The rule

? unwraps success, or returns the failure from this function.

Without ?:

use std::num::ParseIntError;

fn parse_days(input: &str) -> Result<u32, ParseIntError> {
    let days = match input.trim().parse::<u32>() {
        Ok(d) => d,
        Err(e) => return Err(e),
    };
    Ok(days.min(21))
}

With ?, the same function:

fn parse_days(input: &str) -> Result<u32, ParseIntError> {
    let days = input.trim().parse::<u32>()?;
    Ok(days.min(21))
}

What ? does on a Result:

  • Ok(v) → the expression becomes v, and the function carries on.
  • Err(e) → the function returns immediately with Err(e). If the function's error type differs, ? first converts e with From::from (next lesson uses this).

On an Option, ? returns None early instead.

Where ? is allowed: only in a function whose return type can carry the failure: a Result for Result values, an Option for Option values. A plain fn main() returns (), so ? there is a compile error. The fix is to let main return a Result:

fn main() -> Result<(), ParseIntError> {
    let days = parse_days("14")?;
    println!("loan for {days} days");
    Ok(())
}

If main returns an Err, the program prints the error (in its Debug form) and exits with a failure code.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.