Result, Option & the ? Operator in Rust

From the Rust cheat sheet ยท Error Handling ยท verified Jul 2026

Result, Option & the ? Operator

Propagate errors idiomatically with Result<T, E> and the ? operator.

rust
// Result<T, E> โ€” success or error
fn parse_port(s: &str) -> Result<u16, std::num::ParseIntError> {
    let port = s.parse::<u16>()?;   // ? returns early on error
    Ok(port)
}

// Handle Result
match parse_port("8080") {
    Ok(port) => println!("Port: {port}"),
    Err(e) => eprintln!("Error: {e}"),
}

// ? chains multiple fallible operations
fn read_config() -> Result<String, std::io::Error> {
    let contents = std::fs::read_to_string("config.toml")?;
    Ok(contents)
}
๐Ÿ’ก The ? operator replaces verbose match/unwrap patterns โ€” it's the idiomatic way to propagate errors
โšก Implement From<OtherError> for your error type โ€” then ? auto-converts between error types
๐Ÿ“Œ Use Box<dyn Error> as a quick return type when you don't want a custom error enum
๐ŸŸข In production, use the anyhow crate for applications and thiserror for libraries
resultoptionerror-handlingquestion-mark
Back to the full Rust cheat sheet