typestar

Result and ? in Rust

Recoverable errors, and the ? early-return operator.

fn parse_sum(a: &str, b: &str) -> Result<i32, std::num::ParseIntError> {
    let x: i32 = a.parse()?;
    let y: i32 = b.parse()?;
    Ok(x + y)
}

fn main() {
    match parse_sum("3", "4") {
        Ok(total) => println!("sum: {total}"),
        Err(e) => println!("error: {e}"),
    }
}

How it works

  1. parse()? returns early on an error.
  2. The function's error type is the parse error.
  3. match handles Ok and Err at the call site.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
252
Tokens
101
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 61 seconds.

Type this snippet

Step 1 of 4 in Result & the ? operator, step 4 of 15 in Error handling.

← Previous Next →