ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Rust Tutorial• 7 min read

Error Handling: Result<T, E> & The ? Operator

Recoverable errors with Result, propagating errors cleanly with ? and unrecoverable panic!

Rust separates errors into unrecoverable errors (panic!) and recoverable errors modeled as Result<T, E> (Ok(T) or Err(E)), propagating failures using the concise ? operator.

The Result<T, E> Enum & The ? Operator

Result<T, E> variants: Ok(T) contains success data; Err(E) contains failure details.

The ? Operator: If the expression evaluates to Ok(val), it unwraps val. If it evaluates to Err(e), it immediately returns from the enclosing function with Err(e).

Error Propagation with the ? Operator
use std::fs::File;
use std::io::{self, Read};

fn read_username_from_file() -> Result<String, io::Error> {
    // ? operator automatically returns early on error!
    let mut file = File::open("username.txt")?;
    let mut username = String::new();
    file.read_to_string(&mut username)?;
    Ok(username)
}

fn main() {
    match read_username_from_file() {
        Ok(name) => println!("User: {}", name),
        Err(err) => eprintln!("Failed to read file: {}", err),
    }
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What does the `?` operator do when placed after a function returning a `Result<T, E>` in Rust?