Skip to the workspace
Pebellslearn by building
Types and Error Handling  ›  Lesson

Option and Result

Option and Result Enumerations 15 minOption says a value might be missing and Result says an operation might fail, and Rust makes you handle both cases before you can use the value.

rust / Option and Result

Explore each scene at your own pace.

01 · The rule

The rule

Option and Result

Option says a value might be missing and Result says an operation might fail, and Rust makes you handle both cases before you can use the value.

Handle absent values and failures explicitly instead of inventing a sentinel value.

Search the catalogue for a title it does not hold. Type letters where a card number should go. Many languages answer with null or an exception that the caller may forget to handle. Rust has neither. It uses two ordinary enums, and the type system will not let you ignore them.

The rule

Maybe missing → Option; might fail → Result. Handle both arms before use.

Both are enums from the standard library, always in scope:

enum Option<T> { Some(T), None }
enum Result<T, E> { Ok(T), Err(E) }

Option<T>: a value that may be absent, with no reason needed.

fn find(shelf: &[Book], title: &str) -> Option<usize> {
    shelf.iter().position(|b| b.title == title)
}

Result<T, E>: an operation that can fail, and E says why.

let card: Result<u32, _> = "1042".parse::<u32>();   // Ok(1042)
let bad: Result<u32, _> = "10x2".parse::<u32>();    // Err(ParseIntError)

An Option<u32> is not a u32. You cannot add to it or print it as a number until you open it:

match "10x2".parse::<u32>() {
    Ok(card) => println!("lending to card {card}"),
    Err(e) => println!("that is not a card number: {e}"),
}

if let Some(i) = find(&shelf, "Iron Tides") {
    println!("found at position {i}");
}

Handy methods instead of a full match:

  • unwrap_or(default): the value, or a fallback. input.parse::<u32>().unwrap_or(0).
  • unwrap(): the value, or panic (crash) on None/Err.
  • expect("message"): like unwrap, with your message in the panic.
  • ok() turns a Result into an Option; ok_or(err) goes the other way.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.