Sub topic 5
while let: looping while a pattern matches
This chapter assumes you know Option and Result, the match expression, basic patterns, and the basics of ownership and borrowing. It also assumes you have seen if let, which runs a block once when a pattern matches.
The idea
while let is the looping form of if let. It tests a pattern before each pass through the body. If the value matches, the variables in the pattern are bound and the body runs. Then the loop evaluates the expression again. When the pattern fails to match, the loop ends.
The general shape is:
while let PATTERN = EXPRESSION {
// body, with the pattern's bindings in scope
}The pattern is refutable, which means it can fail to match. That failure is the loop's exit condition. An irrefutable pattern would never fail, so the loop would never end, and the compiler warns about it.
A worked example: draining a stack
Vec::pop removes the last element and returns Option<T>. It gives Some(value) while elements remain and None when the vector is empty. That fits while let well.
fn main() {
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
println!("popped {top}");
}
}This prints popped 3, popped 2, popped 1. On the fourth check, pop returns None, the pattern Some(top) does not match, and the loop ends.
The expression after = is evaluated again on every iteration. Here that means stack.pop() runs each time, and it changes the stack. The loop is driven by the source of values, not by a counter.
The same loop with `match`
Without while let, you would write an infinite loop with a match that breaks on the other case:
fn main() {
let mut stack = vec![1, 2, 3];
loop {
match stack.pop() {
Some(top) => println!("popped {top}"),
None => break,
}
}
}Both programs behave the same. The while let version removes the loop, the match, and the break, so the exit condition sits in the loop header.
When to use it
while let suits sources that produce values one at a time and signal the end with a non-matching value:
Vec::popfor stacks and work lists.Iterator::next, when you need to callnextyourself inside the body.Receiver::recvon a channel, which returnsOk(value)until all senders are dropped.- A queue such as
VecDeque::pop_front.
For an ordinary for loop over a collection, prefer for. It handles iteration for you and cannot be misused as easily.
The pattern can also destructure. This loop walks a list of pairs as it consumes them:
fn main() {
let mut jobs = vec![("build", 2), ("test", 5)];
while let Some((name, secs)) = jobs.pop() {
println!("{name} takes {secs}s");
}
}Common errors
- Mutating the source while borrowing it. If you write
while let Some(x) = stack.last(), the referencexborrowsstack. Callingstack.push(...)orstack.pop()in the body whilexis still used causes a borrow error. Usepop, which returns an owned value, or finish usingxbefore you mutate. - An expression that never changes.
while let Some(x) = config.get("key")keeps matching if nothing altersconfig. The loop never ends. Make sure each evaluation moves towardNone. - An irrefutable pattern.
while let x = stack.pop()always matches, becausexjust binds anOption. The compiler warns that the pattern is irrefutable, and the loop runs forever. - Expecting
else.while lethas noelsebranch. If you need code to run after the loop ends, put it after the loop.
Exercise
What does this program print, and why does the loop stop? fn main() { let mut queue = std::collections::VecDeque::from(vec!["a", "b"]); while let Some(item) = queue.pop_front() { println!("{item}"); } }
Show answer
It prints "a" and then "b", each on its own line. popfront removes and returns the first element as Some(item). After both items are removed, popfront returns None, which does not match Some(item), so the loop ends.
Exercise
Rewrite this loop as a while let: loop { match stack.pop() { Some(v) => println!("{v}"), None => break } }
Show answer
while let Some(v) = stack.pop() { println!("{v}"); }