← Back to Rust Course | Chapter 8: Enums & Pattern Matching | Lesson 5 of 7

while let Syntax

while let keeps repeating an action for as long as a value keeps matching the pattern you care about.

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

markup
fn main() {
    let mut stack = vec![1, 2, 3];
    while let Some(top) = stack.pop() {
        println!("Popped: {}", top);
    }
}

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

markup
fn main() {
    let mut queue = vec!["a", "b", "c"];
    while let Some(item) = queue.pop() {
        println!("Processing: {}", item);
    }
    println!("Queue is now empty");
}

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

markup
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);
    }
}

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

markup
fn main() {
    let mut stack = vec![5, 10];
    loop {
        match stack.pop() {
            Some(v) => println!("value: {}", v),
            None => break,
        }
    }
}
Common Mistakes
  1. Forgetting the loop stops automatically the first time the pattern no longer matches -- no manual break is needed for that.
  2. Using while let on a collection when a plain for loop would be simpler and more idiomatic.
  3. Not realizing .pop() on a Vec returns an Option, which is exactly the shape while let Some(x) = ... is designed to consume.
Chapter Summary
  • while let pattern = value { ... } loops as long as value continues to match the given pattern.
  • It commonly pairs with methods returning Option, like Vec::pop(), to process items until none remain.
  • The loop exits automatically the first time the match fails, with no explicit break required for that case.
  • while let reduces boilerplate compared to a manual loop with a match and break inside.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.