Most languages have a special value — null, nil, None — that means "nothing here". It is also the classic source of crashes: you forget to check, and the program dies. Rust takes a different route: there is no null. When a value might be absent, its type says so explicitly: Option<T>.
An Option<T> is always one of exactly two things:
Some(v)— there IS a value, and it'svNone— there is no value
You meet Options immediately when working with vectors. nums.first() and nums.get(i) can't promise an element exists (the vector might be empty, the index might be too big), so they return Option<&i32> instead of a plain number:
let nums = vec![10, 20, 30];
nums.get(1); // Some(&20) — index 1 exists
nums.get(9); // None — out of bounds, but NO crash
Three ways to get the value out:
// 1. if let — run code only when there IS a value (safe)
if let Some(v) = nums.first() {
println!("got {}", v);
}
// 2. unwrap_or — take the value, or a fallback on None (safe)
let x = nums.get(9).unwrap_or(&-1); // x is &-1
// 3. unwrap — take the value, PANIC on None (dangerous)
let y = nums.get(1).unwrap(); // fine: index 1 exists
The trap:
Calling .unwrap() on a None kills your program at runtime. This code compiles fine:
let nums = vec![10, 20, 30];
let tenth = nums.get(9).unwrap(); // get(9) is None...
...and then panics the moment it runs:
thread 'main' panicked at src/main.rs:3:29:
called `Option::unwrap()` on a `None` value
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Read that message carefully — you WILL see it again. The rule: use if let or unwrap_or by default, and save unwrap() for when you can prove the value exists.
Assignment
Follow the Coding Tutorial and practice all three: create let nums = vec![10, 20, 30];, then
- take
nums.first()and print it viaif let Some(v), - take
nums.get(9)and print it via.unwrap_or(&-1), - print
nums.get(1).unwrap()— safe here, because index 1 certainly exists.
The exact expected output is:
first = 10
missing = -1
second = 20
Hint
get returns Option<&i32> — a reference — so the fallback in unwrap_or must be a reference too: &-1.
Free plan: 30 tutor messages. Premium is unlimited.