12 / 35

Core Rust Concepts· 13 min read· Lesson 12 of 35

Option and Result

Part 1 · Rust. Rust has no null. Learn Option for 'maybe a value' and Result for 'it worked or it failed', plus why unwrap and expect are risky.

Some questions don’t always have an answer. “What’s the price of the Unicorn Frappé?” The café doesn’t sell one. Some actions can fail. “Turn the text "4.5O" into a number” fails because someone typed the letter O instead of zero. Good programs handle these cases on purpose instead of crashing. Rust gives you two built-in enums for this: Option and Result.

The billion-dollar mistake: null

Many languages have a special value called null (or nil, or None), meaning “nothing here”. The trouble is that any variable might secretly be null. Forget to check once, and your program crashes. The inventor of null, Tony Hoare, later called it his “billion-dollar mistake”.

Rust has no null. Instead, when a value might be missing, the type says so out loud, and the compiler makes you deal with it.

Option: maybe a value

Option is an ordinary enum from the standard library. It looks like this:

enum Option<T> {
Some(T),
None,
}
  • Some(value) means “there is a value, and here it is”.
  • None means “there’s nothing”.
  • The <T> means it can hold any type: Option<u32>, Option<String>, and so on. T is a placeholder for “some type”, which you’ll study in a later lesson.

Option, Some and None are so common that you can use them without any use line or Option:: prefix.

Café analogy: a pastry case slot. It either has a croissant in it (Some(croissant)) or it’s empty (None). You have to look before you serve.

src/main.rs
fn price_of(item: &str) -> Option<u32> {
match item {
"Latte" => Some(450),
"Espresso" => Some(300),
"Muffin" => Some(300),
_ => None,
}
}
fn main() {
let order = "Latte";
match price_of(order) {
Some(cents) => println!("{order} costs {cents} cents"),
None => println!("Sorry, we don't sell {order}"),
}
}
Output
Latte costs 450 cents

Step by step:

  1. price_of returns Option<u32>. The type itself warns the caller: “you might not get a price”.
  2. For known items we return Some(price), otherwise None.
  3. In main, match handles both cases. The compiler won’t let us forget None.

Why you can’t use an Option as if it were the value

src/main.rs
fn main() {
let price: Option<u32> = Some(450);
let with_tip = price + 50; // error!
}
Output
error[E0369]: cannot add `{integer}` to `Option<u32>`
--> src/main.rs:3:26
|
3 | let with_tip = price + 50; // error!
| ----- ^ -- {integer}
| |
| Option<u32>
|
note: `Option<u32>` does not implement `Add<{integer}>`

An Option<u32> is not a u32. You must open the box first. This is exactly what stops null crashes: you can’t accidentally use a missing value.

Handy ways to open an Option

if let is perfect when you only care about the Some case:

if let Some(cents) = price_of("Muffin") {
println!("Muffin: {cents} cents");
}

unwrap_or gives a fallback value when it’s None:

src/main.rs
fn stamps_for(customer: &str) -> Option<u32> {
if customer == "Priya" { Some(7) } else { None }
}
fn main() {
let priya = stamps_for("Priya").unwrap_or(0);
let stranger = stamps_for("Bob").unwrap_or(0);
println!("Priya: {priya}, Bob: {stranger}");
}
Output
Priya: 7, Bob: 0

Many standard library functions already return Option. For example, .first() on a list returns None when the list is empty:

let menu = ["Latte", "Mocha"];
let first = menu.first(); // Some("Latte") as a reference

Result: it worked, or here’s why not

Option says “maybe nothing”. But when something fails, you usually want to know why. That’s Result:

enum Result<T, E> {
Ok(T),
Err(E),
}
  • Ok(value) means “success, here’s the value”.
  • Err(error) means “it failed, here’s information about what went wrong”.

Analogy: a card payment machine. It either shows “Approved” with a receipt, or “Declined” with a reason like “insufficient funds”.

A real example: turning text into a number with .parse(). Typed input always arrives as text, and the text might not be a number.

src/main.rs
fn main() {
let typed_quantity = "3";
let typo_quantity = "three";
let good: Result<u32, _> = typed_quantity.parse();
let bad: Result<u32, _> = typo_quantity.parse();
println!("{good:?}");
println!("{bad:?}");
}
Output
Ok(3)
Err(ParseIntError { kind: InvalidDigit })
  1. .parse() tries to convert text into the type we ask for, here u32.
  2. It returns a Result. The _ lets Rust work out the error type for us (it’s ParseIntError).
  3. "3" parses fine, so we get Ok(3). "three" doesn’t, so we get an Err describing the problem.

Handling it with match:

src/main.rs
fn main() {
let typed = "2";
match typed.parse::<u32>() {
Ok(quantity) => {
let total_cents = quantity * 450;
println!("{quantity} lattes = {total_cents} cents");
}
Err(error) => println!("That's not a valid quantity: {error}"),
}
}
Output
2 lattes = 900 cents

The ::<u32> after parse is called the turbofish (it looks like a little fish!). It’s another way of telling parse which type you want.

Writing your own function that returns Result

src/main.rs
fn take_beans(stock_g: u32, needed_g: u32) -> Result<u32, String> {
if needed_g > stock_g {
Err(format!("Only {stock_g} g of beans left, need {needed_g} g"))
} else {
Ok(stock_g - needed_g)
}
}
fn main() {
match take_beans(100, 18) {
Ok(left) => println!("Shot pulled! {left} g left"),
Err(message) => println!("Can't make it: {message}"),
}
match take_beans(10, 18) {
Ok(left) => println!("Shot pulled! {left} g left"),
Err(message) => println!("Can't make it: {message}"),
}
}
Output
Shot pulled! 82 g left
Can't make it: Only 10 g of beans left, need 18 g

Here the error type is a String, a simple human-readable message. In Error Handling with ? you’ll build a proper error enum.

Note

Option or Result? Use Option when “nothing” is a normal, expected answer (an item isn’t on the menu). Use Result when something went wrong and the caller deserves an explanation (not enough beans).

unwrap and expect: the emergency exits

Both Option and Result have a method called .unwrap(). It means: “give me the value inside, and if there isn’t one, crash the program”.

src/main.rs
fn main() {
let quantity: u32 = "three".parse().unwrap();
println!("{quantity}");
}
Output
thread 'main' (48213) panicked at src/main.rs:2:41:
called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

The number in brackets after 'main' is a thread ID and will be different on your machine. A panic is Rust stopping the program on purpose because something happened that it can’t continue from. .expect("message") does the same thing but lets you write the panic message:

src/main.rs
fn main() {
let quantity: u32 = "three".parse().expect("quantity should be a number");
println!("{quantity}");
}
Output
thread 'main' (48213) panicked at src/main.rs:2:41:
quantity should be a number: ParseIntError { kind: InvalidDigit }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Warning

Avoid unwrap and expect for anything that can really happen, like bad user input, a missing menu item, or an empty stock list. If a customer types “three” into the order form, the café’s whole app shouldn’t crash. Handle it with match, if let, unwrap_or, or the ? operator coming in two lessons.

When are they okay?

  • In quick experiments and tiny learning programs.
  • In tests.
  • When you’re certain a value exists, and expect with a clear message explains why.

Tip

If you do use one, prefer expect over unwrap. A message like "menu file should always contain a Latte" tells future you exactly which assumption broke.

Try it yourself

  1. Write fn find_table(customer: &str) -> Option<u32> that returns Some(4) for "Sam", Some(7) for "Lee", and None for anyone else. In main, print “Sam is at table 4”, or “No booking for Ana” using match.
Show solution
fn find_table(customer: &str) -> Option<u32> {
match customer {
"Sam" => Some(4),
"Lee" => Some(7),
_ => None,
}
}
fn main() {
for name in ["Sam", "Ana"] {
match find_table(name) {
Some(table) => println!("{name} is at table {table}"),
None => println!("No booking for {name}"),
}
}
}
  1. Write fn tip_cents(text: &str) -> Result<u32, String> that parses the text as a u32. If parsing fails, return Err with the message "Tip must be a whole number of cents". Test it with "150" and "1.50".
Show solution
fn tip_cents(text: &str) -> Result<u32, String> {
match text.parse::<u32>() {
Ok(cents) => Ok(cents),
Err(_) => Err(String::from("Tip must be a whole number of cents")),
}
}
fn main() {
println!("{:?}", tip_cents("150"));
println!("{:?}", tip_cents("1.50"));
}
Output
Ok(150)
Err("Tip must be a whole number of cents")

The _ in Err(_) means “there’s an error value here, but I don’t need it”.

Recap

  • Rust has no null. A value that might be missing has the type Option<T>: Some(value) or None.
  • Result<T, E> is for things that can fail: Ok(value) or Err(error).
  • You must handle both cases before using the value, with match, if let, or helpers like unwrap_or.
  • unwrap and expect panic (crash) on None or Err. Save them for tests, experiments, or truly impossible cases.

What’s next

Next you’ll store many values at once: lists, lookup tables and text. Continue with Collections: Vec, HashMap and String.

0 of 35 lessons complete

Search lessons

Type to search all lessons.