Option and Result

Contents

Option and Result#

Option<T> replaces null; Result<T, E> replaces exceptions. Both are enums in the standard library.

Construct and consume an Option.

let n: Option<u32> = Some(10);
if let Some(v) = n {
    println!("{v}");
}

Define a fallible function returning a Result.

fn parse(s: &str) -> Result<u32, std::num::ParseIntError> {
    s.parse::<u32>()
}

The ? operator early-returns the Err.

let v = parse("42")?;

References#

  • Errors for the wider error-handling surface.

  • Enums for the underlying enum mechanics.