0Pricing
Learn Rust Coding · Lesson

Result and the ? Operator

Propagate errors.

The Result Type

Result<T, E> represents an operation that can succeed with Ok(T) or fail with Err(E). It is Rust's primary error-handling type.

fn main() {
    let parsed: Result<i32, _> = "42".parse::<i32>();
    println!("{:?}", parsed);
}

Matching on Result

You can handle both outcomes explicitly with match.

fn main() {
    match "oops".parse::<i32>() {
        Ok(n) => println!("got {n}"),
        Err(e) => println!("error: {e}"),
    }
}

All lessons in this course

  1. Result and the ? Operator
  2. thiserror
  3. anyhow
  4. Error Conversion
← Back to Learn Rust Coding