Sub topic 10
if let, let else, while let, and matches!
This chapter assumes you know basic Rust syntax, structs and tuples, and the basics of ownership. It also assumes you have met match and Option<T>. A full match is exhaustive, so it can be wordy when you care about only one pattern. Rust has four shorter forms for that case.
Why shorter forms exist
Suppose you only want to act when an Option holds a value. A full match needs an arm that does nothing:
fn main() {
let name: Option<&str> = Some("Ferris");
match name {
Some(n) => println!("hello {n}"),
None => {}
}
}The None => {} arm is noise. The forms below remove it. Each one is a match with a single pattern of interest.
if let
if let runs a block when a value fits one pattern. An optional else handles everything else.
fn first_even(nums: &[i32]) -> Option<i32> {
nums.iter().copied().find(|n| n % 2 == 0)
}
fn main() {
if let Some(n) = first_even(&[1, 3, 5]) {
println!("found {n}");
} else {
println!("nothing found");
}
}The variable n exists only inside the if let block. The trade-off is that the compiler does not check exhaustiveness here. If you later add a variant to the enum, an if let will silently ignore it, while a match would fail to compile.
let else
let else binds variables for the rest of the function and exits early when the pattern fails. The else block must diverge, meaning it ends in return, break, continue, or a panic.
fn parse_pair(s: &str) -> Option<(i32, i32)> {
let Some((a, b)) = s.split_once(',') else {
return None;
};
Some((a.trim().parse().ok()?, b.trim().parse().ok()?))
}
fn main() {
println!("{:?}", parse_pair("3, 4"));
println!("{:?}", parse_pair("3 4"));
}This prints Some((3, 4)) and then None. Compare it with if let. With if let, the happy path sits inside a nested block. With let else, a and b are ordinary variables in the function body, and the failure case is handled up front.
while let
while let repeats as long as the pattern keeps matching. It is the usual way to drain a stack or a queue.
fn main() {
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
println!("popped {top}");
}
}pop returns Some(value) until the vector is empty, then None, which ends the loop. The output is 3, 2, 1.
matches!
matches! is a macro that turns a pattern test into a bool. It does not bind variables you can use afterward, but it accepts ranges, or-patterns, and guards.
fn main() {
println!("{}", matches!('q', 'a'..='z'));
let n = Some(7);
println!("{}", matches!(n, Some(x) if x > 5));
}Both lines print true. Use it in conditions, filters, and assertions:
fn main() {
let letters = ['a', 'B', 'c', '4'];
let lower = letters.iter().filter(|c| matches!(c, 'a'..='z')).count();
println!("{lower}");
}This prints 2.
Choosing between them
Common mistakes
- Using
=where you meant a comparison. Inif let Some(n) = x, the=separates a pattern from a value. It is not assignment. - Writing a
let elseblock that falls through. The compiler rejects it, because the block must not complete normally. - Using
if leton an enum you expect to grow. Prefermatchso the compiler flags new variants. - Expecting
matches!to give you bound values. It returns only abool.
Exercise
Write a function last_digit_or_zero(s: &str) -> u32 that uses let else to take the last character of s and return its digit value, or returns 0 if the string is empty or the last character is not a digit.
Show answer
fn lastdigitorzero(s: &str) -> u32 { let Some(c) = s.chars().last() else { return 0; }; let Some(d) = c.todigit(10) else { return 0; }; d }
Exercise
Which of the four forms would you use to count how many items in a slice of Option<i32> are None, and why?
Show answer
Use matches! inside a filter, for example items.iter().filter(|x| matches!(x, None)).count(). You need only a yes or no answer for each item, and matches! returns a bool without any bindings.