Sub topic 5
while let: looping while a pattern matches
This chapter assumes you know Option and Result, match, the idea of refutable patterns from the earlier chapters, and basic ownership and borrowing. It also assumes you have used if let. while let is the loop version of the same idea.
What while let does
while let evaluates an expression on every iteration and tests the result against a refutable pattern. If the pattern matches, the loop body runs with the pattern's bindings in scope. If it doesn't match, the loop ends.
fn main() {
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
println!("popped {top}");
}
}Vec::pop returns Some(value) while the vector has items and None once it is empty. The loop prints 3, 2, 1 and then stops.
The scrutinee (the expression after =) is evaluated again on every pass. That is why it is usually a call with side effects, such as pop(), next() or recv(). Each call produces a fresh value for the pattern to test.
The desugaring
while let is shorthand for a loop with a match that breaks on the non-matching case:
fn main() {
let mut stack = vec![1, 2, 3];
loop {
match stack.pop() {
Some(top) => println!("popped {top}"),
_ => break,
}
}
}This is the same program as the previous one. The shorthand removes the _ => break arm and one level of nesting. Because the expansion is a plain loop, break, continue and loop labels work in the body exactly as they do elsewhere.
Two consequences follow from this:
- There is no
elsebranch. The "no match" case always means "leave the loop". If you need different behavior, useloopwithmatch, orloopwithlet else. - A
breakinside the body leaves thewhile letloop. It does not leave a surroundingmatch.
Refutable patterns only
The pattern must be refutable, meaning it can fail to match. If you write an irrefutable pattern, the loop can never end through the pattern, and the compiler warns with the irrefutable_let_patterns lint. This is a sign you meant something else.
The opposite mistake is a refutable pattern that always matches in practice. This loop never ends:
fn main() {
let items = vec![1, 2, 3];
// Never terminates: first() does not remove anything.
while let Some(first) = items.first() {
println!("first is {first}");
break; // without this line the program loops forever
}
}The loop ends only if something in the body changes what the scrutinee returns, or if the body breaks. pop() works because the call itself consumes an item. first() and last() only look.
Common sources of values
Collections used as stacks or queues
A Vec with pop() gives you a stack. A VecDeque with pop_front() gives you a queue. Both fit while let well.
Work lists
A while let loop can add new items while it consumes them. This makes it a natural fit for traversing trees and graphs without recursion:
struct Node {
value: i32,
children: Vec<Node>,
}
fn sum(root: &Node) -> i32 {
let mut total = 0;
let mut pending = vec![root];
while let Some(node) = pending.pop() {
total += node.value;
pending.extend(node.children.iter());
}
total
}
fn main() {
let tree = Node {
value: 1,
children: vec![
Node { value: 2, children: vec![] },
Node {
value: 3,
children: vec![Node { value: 4, children: vec![] }],
},
],
};
println!("{}", sum(&tree));
}This prints 10. Pushing inside the body is allowed because pop() returns an owned Option<&Node>. The mutable borrow of pending ends as soon as pop() returns, so the body can use pending again.
Channels
Receiver::recv blocks until a message arrives. It returns Err once every sender has been dropped and the buffer is empty. That is a clean end condition:
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
let producer = thread::spawn(move || {
for i in 1..=3 {
tx.send(i * 10).unwrap();
}
});
while let Ok(msg) = rx.recv() {
println!("got {msg}");
}
producer.join().unwrap();
}The move closure takes ownership of tx. When the thread finishes, tx is dropped, recv returns Err, and the loop ends. If you forgot to drop a sender (for example, by keeping an extra clone in main), this loop would block forever.
Iterators: usually use for instead
You can write while let Some(x) = iter.next(), but a for loop does the same thing with less code. Prefer for when you consume the whole iterator and don't touch it in the body.
while let with an iterator is worth it when the body needs the iterator itself. A typical case is a tokenizer that looks ahead with peekable:
fn main() {
let text = "123+45";
let mut chars = text.chars().peekable();
let mut digits = String::new();
while let Some(&c) = chars.peek() {
if !c.is_ascii_digit() {
break;
}
digits.push(c);
chars.next();
}
println!("{digits}");
println!("{:?}", chars.next());
}This prints 123 and then Some('+'). A for loop would own the iterator and make chars.next() and chars.peek() in the body impossible. The pattern Some(&c) copies the char out of the reference returned by peek. Since c is a plain char, the borrow of chars ends right after the pattern is matched, so chars.next() in the body compiles.
Bindings and moves
The bindings from the pattern exist only for one pass of the body. They are new variables on each iteration, so they don't shadow anything across iterations. A name that shadows an outer variable hides it only inside the body.
Moves follow normal pattern rules. If the scrutinee is an owned value and the pattern binds by value, the matched part moves into the binding. In while let Some(top) = stack.pop(), top owns the popped value. If you match on a reference, as with pending.pop() above where items are &Node, bindings are references and nothing is moved out of the original data.
Borrowing pitfalls
The scrutinee's borrow lasts as long as any binding that refers into it. This fails to compile:
fn main() {
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.last() {
println!("top is {top}");
stack.pop(); // error: cannot borrow `stack` as mutable
}
}last() returns Option<&i32>, so top is a reference into stack. It is still alive when stack.pop() needs a mutable borrow. Two fixes work. One is to copy the value out first with Some(&top), which ends the borrow immediately for Copy types. The other is to switch to while let Some(top) = stack.pop() so the loop owns each value.
Temporaries live for the whole body
Temporaries created in the scrutinee are dropped at the end of the loop body, not at the end of the scrutinee expression. Edition 2024 changed temporary scope for if let, but not for while let. This matters most with lock guards:
use std::sync::Mutex;
fn main() {
let queue = Mutex::new(vec![1, 2, 3]);
// The MutexGuard lives until the end of each iteration's body,
// so the lock is held while the body runs.
while let Some(job) = queue.lock().unwrap().pop() {
println!("job {job}");
// calling queue.lock() here would deadlock
}
}To release the lock before the body runs, take the value in a separate statement. let else keeps this tidy:
use std::sync::Mutex;
fn main() {
let queue = Mutex::new(vec![1, 2, 3]);
loop {
let next = queue.lock().unwrap().pop();
let Some(job) = next else {
break;
};
println!("job {job}");
}
}Here the guard is dropped at the end of the let next statement. This costs a few more lines, but the body can lock the queue again without deadlocking.
while let with let chains
With Rust 1.88 or newer and edition = "2024", a while condition can be a let chain. You can add boolean tests with &&:
// Requires Rust 1.88 or newer and edition = "2024" in Cargo.toml.
fn main() {
let mut stack = vec![5, 4, 0, 3, 2];
while let Some(top) = stack.pop()
&& top != 0
{
println!("popped {top}");
}
println!("left: {stack:?}");
}This prints popped 2, popped 3, and then left: [5, 4]. The 0 was popped before the test top != 0 failed, so it is gone from the stack. A failed chain link ends the loop, but any side effect from evaluating earlier links has already happened. If you need to inspect a value without removing it, use peek or last for the check, or check inside the body and break.
Choosing between while, for and loop
| Situation | Best fit |
|---|---|
| Consume every item of an iterator | `for` |
| Pop from a stack or queue that the body may refill | `while let` |
| Read from a channel until senders close | `while let Ok(..)` |
| Look ahead with `peek` and sometimes stop | `while let Some(&..)` |
| Need different handling when the pattern fails | `loop` with `match` or `let else` |
| Stop on a plain boolean condition | `while` |
Summary of rules
while let PATTERN = EXPR { body }repeats whilePATTERNmatchesEXPR, and it is shorthand forloopplusmatchwith abreakarm.- There is no
elsebranch. The loop ends on the first non-match. - The scrutinee is re-evaluated on each pass, so it should have an effect that moves the loop toward ending.
- Borrows in bindings last through the body, and temporaries in the scrutinee last until the end of the body.
- Let chains in
whileneed Rust 1.88 and edition 2024.
Exercise
A worker loop is written as while let Some(job) = queue.lock().unwrap().pop() { run(job); }, where run also calls queue.lock() to add follow-up jobs. The program hangs. Why does it hang, and how do you fix it?
Show answer
The MutexGuard returned by lock().unwrap() is a temporary in the scrutinee. In while let, scrutinee temporaries live until the end of the loop body, so the lock is still held when run calls queue.lock() again, and the thread deadlocks on itself. Fix it by taking the job in a separate statement so the guard is dropped first: loop { let next = queue.lock().unwrap().pop(); let Some(job) = next else { break }; run(job); }.
Exercise
What does this program print, and which Rust version and edition does it need? let mut v = vec![1, 2, 9, 3]; while let Some(x) = v.pop() && x < 5 { println!("{x}"); } println!("{v:?}");
Show answer
It prints 3, then [1, 2]. The loop pops 3 (passes the test and prints), then pops 9, which fails x < 5 and ends the loop. The 9 has already been removed from the vector. A while let chain needs Rust 1.88 or newer and edition = "2024".