typestar

The ? operator in Rust

? returns the error early, so the happy path reads as a straight line.

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

fn middle(line: &str) -> Option<char> {
    let word = line.split(' ').nth(1)?;
    let mid = word.len() / 2;
    word.chars().nth(mid)
}

fn main() {
    println!("{:?}", sum_of("1", "2", "3"));
    println!("{}", sum_of("1", "two", "3").is_err());
    println!("{:?}", middle("the quick fox"));
}

How it works

  1. It works in any function returning Result or Option.
  2. On Err it returns immediately, converting the error type.
  3. Chaining several calls needs no match at all.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
437
Tokens
194
Three-star pace
100 tpm

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

Type this snippet

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

← Previous Next →