Sub topic 10
if let, let else, while let, and matches!
This chapter assumes you can read match expressions, know that Option<T> is an enum with Some and None, and understand moves and references at a basic level. A full match is the general tool for taking an enum apart. Often you only care about one variant, and a full match with a throwaway _ => {} arm is noisy. Rust provides four shorthand forms for these cases, and each one is built on the same pattern syntax you already know.
Refutable and irrefutable patterns
A pattern is irrefutable if it matches every possible value of its type. The x in let x = 5; and the (a, b) in let (a, b) = pair; are irrefutable. A pattern is refutable if some values do not match it. Some(n) is refutable because the value might be None.
Plain let and function parameters accept only irrefutable patterns. Writing let Some(x) = maybe; is a compile error, because the compiler cannot decide what to do for None. The four constructs in this chapter exist to accept a refutable pattern and give you a way to handle a mismatch.
| Construct | Use it when | If the pattern does not match |
|---|---|---|
| `if let` | You want to run a block for one case | Skips the block, or runs an `else` block |
| `let else` | You need the bound values for the rest of the function | Runs an `else` block that must leave the current flow |
| `while let` | You want to loop for as long as a pattern keeps matching | Ends the loop |
| `matches!` | You only need a `bool` answer | Evaluates to `false` |
if let
if let PATTERN = EXPRESSION { ... } tests the pattern against the value. If it matches, the names in the pattern are bound inside the block. An optional else block handles every other case.
fn first_even(nums: &[i32]) -> Option<i32> {
nums.iter().copied().find(|n| n % 2 == 0)
}
fn main() {
match first_even(&[1, 3, 4, 6]) {
Some(n) => println!("first even: {n}"),
None => println!("no even number"),
}
if let Some(n) = first_even(&[1, 3, 5]) {
println!("found {n}");
} else {
println!("nothing found");
}
}The match and the if let do the same job here. The difference is that if let is shorter when one arm carries the logic.
Keep these points in mind:
if letis amatchwith a wildcard arm, so the compiler does not check exhaustiveness for you. If you later add a variant to the enum, anif letsilently treats it as "no match". Amatchwould stop compiling and point you at the spot.- The bound names exist only inside the block. They are not visible after it.
else if letchains work, and you can mix them with plainelse ifconditions.- The expression is a place or value that the pattern may move out of. This matters for owned data and is covered below.
let else
if let nests your main logic one level deeper. When the happy path is the rest of the function, let else keeps it flat. You write the pattern, then an else block that handles the mismatch.
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"));
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
println!("popped {top}");
}
println!("{}", matches!('q', 'a'..='z'));
}The program prints Some((3, 4)), then None, then popped 3, popped 2, popped 1, and finally true.
Two rules define let else:
- The
elseblock must diverge. It has to end inreturn,break,continue, apanic!, or another expression of type!. It cannot fall through, because the namesaandbmust be bound when execution continues past the statement. - The bound names are in scope for the rest of the enclosing block, not only inside a nested block.
Inside a loop, let else pairs well with continue. It lets you skip bad items without nesting:
fn main() {
let lines = ["1,2", "oops", "5,6"];
for line in lines {
let Some((a, b)) = line.split_once(',') else {
println!("skipping {line}");
continue;
};
println!("a={a} b={b}");
}
}A related limit: the expression on the right of a let else cannot end in a } that belongs to a block-like expression such as an if or match. Wrap it in parentheses or assign it to a variable first.
while let
while let repeats a block as long as the pattern matches. The classic use is draining a collection where each step returns an Option. In the example above, stack.pop() returns None once the vector is empty, and the loop ends.
It also works well with enums that carry commands. In this example, a break inside the loop stops processing early:
use std::collections::VecDeque;
enum Task {
Print(String),
Stop,
}
fn main() {
let mut queue = VecDeque::from([
Task::Print("a".to_string()),
Task::Stop,
Task::Print("b".to_string()),
]);
while let Some(task) = queue.pop_front() {
match task {
Task::Print(text) => println!("{text}"),
Task::Stop => break,
}
}
println!("left over: {}", queue.len());
}This prints a and then left over: 1. The loop pulled Print("a"), then Stop, and broke out before touching Print("b").
For plain iteration, prefer for item in collection. while let Some(x) = iter.next() is only worth writing when the loop body also needs to call next() itself, or when the source is not an iterator, as with pop.
One edge case catches people. Temporaries created in the scrutinee expression live until the end of the loop body. If you write while let Some(x) = shared.lock().unwrap().pop(), the mutex guard stays locked for the whole iteration. Take the value out in a separate statement if the body needs the lock released.
matches!
matches!(expression, pattern) expands to a match that returns true for the pattern and false otherwise. It accepts everything a match arm accepts, including or-patterns and an if guard.
fn main() {
let words = ["apple", "", "42", "kiwi"];
let count = words
.iter()
.filter(|w| matches!(w.chars().next(), Some('a'..='z')))
.count();
println!("{count}");
let reading = Some(7);
println!("{}", matches!(reading, Some(n) if n > 5));
println!("{}", matches!('Q', 'a'..='z' | 'A'..='Z'));
}This prints 2, true, and true. matches! is the right tool inside filter, assert!, and other places that need a boolean. Names bound in the pattern are visible only to the guard. You cannot use them afterwards, so reach for if let when you need the value.
Choosing between them
If you need to handle three or more cases, or you want the compiler to flag newly added variants, go back to a full match.
Moves in these forms
These constructs bind names the same way match does. If the value is owned and the pattern binds a non-Copy field, the field moves out. Matching on a reference borrows instead:
enum Message {
Text(String),
Quit,
}
fn main() {
let msg = Message::Text(String::from("hello"));
if let Message::Text(s) = &msg {
println!("borrowed: {s}");
}
if let Message::Text(s) = msg {
println!("moved: {}", s.len());
}
// msg is partly moved here and cannot be used again.
}The first if let borrows msg and leaves it usable. The second moves the String out. Add the & when you want to test a value and keep it.
Common mistakes
- Using
if letwhere amatchwould catch a new variant at compile time. - Writing a
let elseblock that prints a message but does not return, which fails with "elseclause oflet...elsedoes not diverge". - Holding a lock guard across a
while letbody by callinglock()in the scrutinee. - Moving a value out with
if letand then using the original variable. - Expecting names bound in
matches!to be usable after the macro call.
Exercise
Why does let Some(x) = maybe else { println!("none"); }; not compile, and what is the smallest fix?
Show answer
The else block of a let else must diverge, but println! returns () and lets execution continue with x unbound. Add a diverging statement such as return; (or continue; or break; inside a loop) after the println!.
Exercise
Write a one-line expression using matches! that is true when an Option<i32> named v holds an even number.
Show answer
matches!(v, Some(n) if n % 2 == 0)