Using Result and Option

Rust encourages handling errors explicitly using Result and Option enums.

The Option Enum

let some_number = Some(5);
let no_number: Option = None;

Used when a value may or may not exist.

The Result Enum

use std::fs::File;

let file = File::open("hello.txt");

This returns Result<T, E>, which can be Ok(T) or Err(E).

Pattern Matching

match file {
    Ok(f) => println!("File opened successfully"),
    Err(e) => println!("Error: {}", e),
}
← PrevNext →