Sub topic 4
Handling variants with match, if let, and let else
This chapter assumes you know basic Rust syntax, enums, match expressions, and ownership basics. You have seen that Option<T> and Result<T, E> are enums. Here you will learn the three ways to look inside them and act on each variant.
match: the complete check
match must cover every variant. If you leave one out, the code does not compile. This is how Rust makes you deal with the missing or failed case.
fn first_even(nums: &[i32]) -> Option<i32> {
nums.iter().copied().find(|n| n % 2 == 0)
}
fn main() {
match first_even(&[1, 3, 4, 5]) {
Some(n) => println!("found {n}"),
None => println!("no even number"),
}
}Each arm binds the inner value to a name, such as n. The same approach works for Result, with Ok(v) and Err(e) arms.
use std::num::ParseIntError;
fn parse_port(s: &str) -> Result<u16, ParseIntError> {
s.trim().parse::<u16>()
}
fn main() {
match parse_port("8080") {
Ok(port) => println!("port {port}"),
Err(e) => println!("error: {e}"),
}
}if let: one variant only
When you care about a single variant, if let is shorter than a full match. The other variants are ignored, or handled in an optional else block.
fn main() {
let maybe: Option<i32> = Some(7);
if let Some(n) = maybe {
println!("n = {n}");
}
}The trade-off is that the compiler no longer forces you to consider the other variants. Use if let only when ignoring them is a deliberate choice.
let else: exit early
let else binds the value when the pattern matches. If it does not match, the else block runs, and that block must leave the current scope with return, break, continue, or a panic.
fn describe(input: Option<&str>) -> String {
let Some(text) = input else {
return String::from("nothing");
};
format!("got {text}")
}
fn main() {
println!("{}", describe(Some("data")));
println!("{}", describe(None));
}Unlike if let, the bound name text is available in the rest of the function. This avoids nesting the main logic inside an if block.
Choosing between them
| Form | Handles | Best for |
|---|---|---|
| `match` | All variants, each with its own logic | Both outcomes matter |
| `if let` | One variant, others ignored or in `else` | Optional side effect |
| `let else` | One variant, others must exit | Early return, flat code |
Common errors
- Non-exhaustive patterns. A
matchmissingNoneorErr(_)fails to compile. Add the arm, or use_if you truly do not need the value. - A
let elseblock that falls through. Theelseblock must diverge. If it ends without returning, the compiler rejects it. - Moving the value. Matching on
Some(s)wheresis aStringmoves it out of theOption. The chapter onas_refandtakecovers how to avoid this.
Exercise
A function receives Option<&str> and must return early with an empty string when the value is None, then use the text in the rest of the function. Which form should you use, and why?
Show answer
Use let else. The else block returns the empty string when the value is None. When the value is Some, the text stays bound for the rest of the function, so the main logic is not nested inside an if.
Exercise
What happens if a match on a Result<u16, ParseIntError> has only an Ok(port) arm?
Show answer
The code does not compile, because the match is not exhaustive. You must also handle Err, either with an Err(e) arm or a _ wildcard arm.