Result<T, E> (Rust)

Result<T, E> is Rust's type for operations that can fail. It is an enum with Ok(value) for success and Err(error) for failure. Rust uses it instead of exceptions for recoverable errors.

Rust

Functions that can fail return Result<T, E> rather than throwing. The caller must acknowledge both outcomes, which makes error paths explicit in the type signature and impossible to forget. T is the success type, E the error type.

Handle a Result with match, or propagate it with the ? operator, which returns early on Err and unwraps on Ok. Helpers like .unwrap_or(default), .map_err(), and .expect(msg) cover common cases. .unwrap() panics on Err.

Use Result for recoverable failures (file not found, parse error) and panic!/unwrap only for bugs or truly unrecoverable states. This separation — Result for expected failure, panic for programmer error — is central to idiomatic Rust error handling.

Syntax

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

Examples

Rust

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

Output:

Ok(42)
true

Learn it in a lesson

See also

Back to the Dictionary