Sub topic 4
Handling variants with match, if let, and let else
This chapter assumes you know basic Rust syntax, enums, and ownership. You should also have read the previous chapters, which introduced Option<T> and Result<T, E> as ordinary enums. Here you learn the three constructs that take those values apart: match, if let, and let else. They differ in how much of the value you must handle and in what happens to the code after them.
Why pattern matching is the main tool
Option has two variants, Some(T) and None. Result has two, Ok(T) and Err(E). You can't call T methods on an Option<T> directly. You first have to check which variant you hold and extract the payload. A pattern does both in one step: it tests the variant and binds the inner value to a name.
The compiler checks that your patterns are exhaustive. If you leave out a variant, the program does not compile. This check is what replaces null checks and exception handlers. You can't forget the failure case, because the code won't build until you handle it.
match: handle every variant
match compares a value against a list of arms. Each arm is a pattern, =>, and an expression. The whole match is itself an expression, so every arm must produce the same type.
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"),
}
}The same shape works for Result. The Err arm gives you the error value, so you can report why the operation failed.
use std::num::ParseIntError;
fn parse_port(s: &str) -> Result<u16, ParseIntError> {
s.trim().parse::<u16>()
}
fn main() {
for input in ["8080", "abc", "70000"] {
match parse_port(input) {
Ok(port) => println!("{input:?} -> port {port}"),
Err(e) => println!("{input:?} -> error: {e}"),
}
}
}This prints a port for "8080", "invalid digit found in string" for "abc", and "number too large to fit in target type" for "70000". The third case shows that one Err type can cover several distinct failures.
Guards, literals, and nested patterns
Patterns can match specific values inside a variant. A guard (if condition after the pattern) adds a runtime test. The compiler does not reason about guards when it checks exhaustiveness, so you still need an arm that catches everything left over.
use std::num::ParseIntError;
fn classify(port: Result<u16, ParseIntError>) -> &'static str {
match port {
Ok(0) => "reserved",
Ok(p) if p < 1024 => "privileged",
Ok(_) => "ordinary",
Err(_) => "invalid",
}
}
fn describe(v: Option<Result<i32, String>>) -> String {
match v {
Some(Ok(n)) => format!("number {n}"),
Some(Err(msg)) => format!("error: {msg}"),
None => String::from("absent"),
}
}
fn main() {
println!("{}", classify("80".parse()));
println!("{}", classify("9000".parse()));
println!("{}", describe(Some(Err(String::from("bad")))));
println!("{}", describe(None));
}Arms are tried top to bottom. Ok(0) and the guarded arm must come before Ok(_), or they would never run. The compiler warns about unreachable arms.
The wildcard trap
_ matches anything. Writing Err(_) is fine when you truly don't care about the error. It also throws the error away, which makes debugging harder. A trailing _ => arm on your own enum has a worse effect: when you add a variant later, the compiler no longer points out the places that need updating. For enums you control, list the variants explicitly.
if let: handle one variant
When you care about only one variant, a full match is noisy. if let runs a block when the pattern matches and skips it otherwise. An optional else handles everything else.
fn main() {
let maybe: Option<i32> = Some(7);
if let Some(n) = maybe {
println!("n = {n}");
} else {
println!("nothing here");
}
}The trade-off is that if let is not exhaustive. The compiler no longer reminds you about the variants you skipped, so use it only when ignoring them is the intent.
while let applies the same idea to a loop. It repeats until the pattern stops matching, which suits Iterator::next and Vec::pop.
fn main() {
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
println!("{top}");
}
}let else: unwrap or leave
With if let, the bound name exists only inside the block. Code that needs the value afterwards ends up nested. let else reverses this: the name is bound in the surrounding scope, and the else block handles the mismatch.
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));
}The else block must diverge. It has to end in return, break, continue, or a panic, so control never falls through with text unbound. If it does not diverge, the compiler rejects it. This makes let else a good fit for guard clauses at the top of a function and for skipping bad items in a loop.
fn sum_valid(lines: &[&str]) -> u32 {
let mut total = 0;
for line in lines {
let Ok(n) = line.trim().parse::<u32>() else {
continue;
};
total += n;
}
total
}
fn main() {
println!("{}", sum_valid(&["10", " 20 ", "oops", "-3", "5"]));
}This prints 35. The "oops" and "-3" lines fail to parse as u32 and are skipped. Note that let else discards the error here. If you need to log it, use match.
Choosing between the three
| Construct | Exhaustive? | Binding visible | Use when |
|---|---|---|---|
| `match` | Yes | Inside each arm | Every variant needs different handling |
| `if let` | No | Inside the block | One variant matters and the rest can be ignored |
| `let else` | No | After the statement | The happy path continues and the other case exits |
For a plain yes/no test, matches! returns a bool and supports guards:
fn main() {
let port: Result<u16, std::num::ParseIntError> = "80".parse();
println!("{}", matches!(port, Ok(p) if p > 1024));
}This prints false, because 80 is not above 1024.
Patterns and ownership
A pattern that binds by value moves the payload out of the matched value. For Option<String>, a match on name itself moves the String into the arm's binding, and name can't be used afterwards. If you only want to look, match on a reference. Default binding modes then make the bound name a reference too.
fn main() {
let name: Option<String> = Some(String::from("Ferris"));
match &name {
Some(n) => println!("hello {n}"),
None => println!("anonymous"),
}
println!("{name:?}");
}Here n is a &String, so name is still usable on the last line. The later chapter on as_ref, as_mut, and take covers the method forms of the same idea.
Common errors
- Non-exhaustive patterns. Forgetting
NoneorErr(_)gives error E0004. Add the arm. Don't add a catch-all that hides the case. - Use of moved value. Matching an owned
Option<String>and then using it again. Match on&name, or callname.as_ref(). - Arms with different types.
Some(n) => nnext toNone => "none"fails. Make every arm yield the same type. - Unreachable arms. A broad pattern placed above a specific one shadows it. Order arms from most specific to least.
let elsethat falls through. Theelseblock must end withreturn,break,continue, or a panic.
Exercise
Write a function first_number(words: &[&str]) -> Option<u32> that returns the first word that parses as a u32, using a for loop and let else to skip words that don't parse. What does first_number(&["a", "12", "7"]) return?
Show answer
Use for w in words { let Ok(n) = w.parse::<u32>() else { continue; }; return Some(n); } and finish the function with None. The call returns Some(12), because "a" fails to parse and continue skips it. "12" is the first word that parses, so the function returns before reaching "7".
Exercise
A function receives Option<&str> and must print the text if it is present. If it is missing, the function must return early with no output. Which construct fits best, and why would a plain if let be less suitable when more code follows?
Show answer
let else fits best: let Some(text) = input else { return; };. The name text stays in scope for the rest of the function. With if let, all the following code would have to sit inside the block, which nests the happy path.