Plenty of questions have no answer some of the time. What is the third session in a log that has two? Which session is the first one longer than an hour, when none are? Many languages answer with a special "nothing" value, often called null, that looks like a normal value until the program tries to use it and crashes. Rust has no null. Instead, a value that may be missing has its own type, and the compiler makes you handle the missing case before you can reach the value.
That type is Option<T>, an enum like the ones you wrote yesterday. T stands for the type of the value inside. Some(value) carries a value and None means there is none. Vector positions start at zero, and get(index) returns Some with a reference to the item when the index is in bounds, or None when it is not. Compare that with durations[2] from Day 4, which panics on a short vector.
Predict and run
Which position is the last valid one? What happens at index 2?
fn main() {
let durations = vec![20, 35];
for index in [1, 2] {
match durations.get(index) {
Some(minutes) => println!("Found {minutes} minutes"),
None => println!("No session there"),
}
}
}Check your prediction
Found 35 minutes
No session thereA vector of length 2 has valid indexes 0 and 1, so index 2 produces None and the program carries on. The Some(minutes) pattern unpacks the value and names it for that arm only; outside the arm, there is no minutes to misuse.
Change the declaration to let durations: Vec<u32> = vec![];. Predict both lines before you run: an empty vector has no valid index at all.
An Option is not the value inside
The point of Option is that you cannot skip the check. If you try to treat the result of get as a number, the program does not compile:
let first: u32 = durations.get(0);error[E0308]: mismatched types
expected `u32`, found `Option<&{integer}>`The types differ on purpose. To get at the number you must say what happens when it is absent. When you only care about the Some case, if let is a shorter form of a two-arm match: it runs the block when the pattern matches and skips it otherwise. You can add else for the None case.
You can also return an Option from your own functions. This one searches for the first long session and returns None if the loop finishes without finding one.
fn first_long(durations: &Vec<u32>, minimum: u32) -> Option<u32> {
for minutes in durations {
if *minutes >= minimum {
return Some(*minutes);
}
}
None
}
fn main() {
let durations = vec![15, 50, 70];
if let Some(minutes) = first_long(&durations, 45) {
println!("First long session: {minutes} min");
}
if let Some(minutes) = first_long(&durations, 90) {
println!("First very long session: {minutes} min");
} else {
println!("No session reaches 90 min");
}
}First long session: 50 min
No session reaches 90 minreturn Some(*minutes) leaves the function as soon as a match is found, so 70 is never examined. The final None is the function's last expression, reached only when nothing qualified. Returning 0 instead would be a trap: a caller could not tell "no session" from "a session of zero minutes".
Fall back to a default
Sometimes a missing value has a sensible stand-in. unwrap_or(default) returns the value inside Some, or the default for None.
fn first_long(durations: &Vec<u32>, minimum: u32) -> Option<u32> {
for minutes in durations {
if *minutes >= minimum {
return Some(*minutes);
}
}
None
}
fn main() {
let empty: Vec<u32> = Vec::new();
let longest_start = first_long(&empty, 30).unwrap_or(0);
println!("Start with {longest_start} min");
}Start with 0 minYou will also see unwrap(), which returns the value or stops the program with called Option::unwrap() on a None value. It is a statement that None cannot happen here. In a program that reads real input, that is rarely true, so prefer match, if let or unwrap_or.
Ask what None means
Before handling an Option, say aloud what None means in your program: "the queue is empty", "no session qualifies". That sentence usually tells you whether to print a message, use a default or stop.
Practice
Your turn
Use get(0) to show the first item in vec!["read", "review"]. Print First: read or Queue is empty as appropriate. Test the empty case with let tasks: Vec<&str> = vec![];.
fn main() {
let tasks = vec!["read", "review"];
println!("{tasks:?}");
}Hint 1: the idea
An empty vector has no valid position, including position zero.
Hint 2: a first step
Use match tasks.get(0) and give the Some arm a name for the returned item.
Worked solution
fn main() {
let tasks = vec!["read", "review"];
match tasks.get(0) {
Some(task) => println!("First: {task}"),
None => println!("Queue is empty"),
}
}First: readWith the empty vector the None arm prints Queue is empty, where tasks[0] would have panicked. The same shape works for any lookup that can come back empty. Next you will meet Result, which is like Option but also says why something failed.
Completion is saved in this browser only. It does not measure mastery.