while let Syntax
while let keeps repeating an action for as long as a value keeps matching the pattern you care about.In this page:
Basic while let
while let repeats its block for as long as the given pattern keeps matching the value, checked fresh at the start of every iteration.
Example: Basic while let
fn main() {
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
println!("Popped: {}", top);
}
}
Login to try C/C++/Java/PHP code in the editor
Draining a Queue-like Structure
while let is especially handy for repeatedly pulling items from a structure until it is empty, since .pop() naturally returns None once nothing is left.
Example: Draining a Queue-like Structure
fn main() {
let mut queue = vec!["a", "b", "c"];
while let Some(item) = queue.pop() {
println!("Processing: {}", item);
}
println!("Queue is now empty");
}
Login to try C/C++/Java/PHP code in the editor
while let With a Custom Enum
while let works with any enum pattern, not just Option, as long as each iteration produces a new value to test against the pattern.
Example: while let With a Custom Enum
enum Fetch {
Item(i32),
Empty,
}
fn main() {
let mut values = vec![10, 20, 30];
let mut next = || values.pop().map_or(Fetch::Empty, Fetch::Item);
while let Fetch::Item(v) = next() {
println!("Got item: {}", v);
}
}
Login to try C/C++/Java/PHP code in the editor
Comparing to a Manual loop
Without while let, the same logic requires a loop combined with a match and an explicit break in the None arm -- while let expresses this common pattern far more concisely.
Example: Comparing to a Manual loop
fn main() {
let mut stack = vec![5, 10];
loop {
match stack.pop() {
Some(v) => println!("value: {}", v),
None => break,
}
}
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting the loop stops automatically the first time the pattern no longer matches -- no manual break is needed for that.
- Using
while leton a collection when a plainforloop would be simpler and more idiomatic. - Not realizing
.pop()on aVecreturns anOption, which is exactly the shapewhile let Some(x) = ...is designed to consume.
while let pattern = value { ... }loops as long asvaluecontinues to match the given pattern.- It commonly pairs with methods returning
Option, likeVec::pop(), to process items until none remain. - The loop exits automatically the first time the match fails, with no explicit
breakrequired for that case. while letreduces boilerplate compared to a manualloopwith amatchandbreakinside.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: