Result<T, E> is Ok or Err. The ? operator returns early on Err, keeping the happy path clean.

Program

Play the program to parse and sum comma-separated numbers.

result.rs
Replay: real traced execution (multi-file project)
fn main() {
    match parse_total("10,20,30") {
        Ok(total) => println!("{total}"),
        Err(e) => println!("error: {e}"),
    }
}

fn parse_total(input: &str) -> Result<i32, std::num::ParseIntError> {
    let mut total = 0;
    for part in input.split(',') {
        total += part.parse::<i32>()?;
    }
    Ok(total)
}
  1. total ← 0

    8fn parse_total(input: &str) -> Result<i32, std::num::ParseIntError> {9    let mut tota→ 0l = 0;10    for part in input.split(',') {
  2. total ← 10

    pass 1 of 3
    9let mut total = 0;10for par"10"t in input.split(',') {11    tota→ 10l += part.parse::<i32>()?;12}
    All 3 passes — pass 1 is the card above
    passparttotal
    1"10"0 10
    2"20"10 30
    3"30"30 60
  3. Ok(total)

    12    }13    Ok(tota60l)14}

Follow the Parse

  1. The input text is split into comma-separated pieces.
  2. Each piece is parsed as a number.
  3. ? stops the function at the first bad piece.
  4. If every piece parses, the function returns Ok(total).
all numbers valid -> add them -> Ok(total)
bad field found  -> stop now -> Err(error)
Result `Result<T, E>` reports success (`Ok`) or failure (`Err`).
? operator `parse::<i32>()?` returns early if parsing fails.
Ok `Ok(total)` wraps the successful result.

Exercise: result.rs

Parse three comma-separated numbers, let ? stop on the first bad field, and return the sum on success