skip to content

In Rust, how does `while let Some(name) = stack.pop()` drain a work stack, and why may its body push onto `stack`?

level: middleimportance: should knowfreq 58%

answer

  1. pattern tested every iteration
  2. None ends the loop
  3. pop hands back an owned value
  4. for over &stack keeps a borrow

basics

~20 s

while let calls stack.pop() before every iteration and runs the body while it returns Some(name), stopping at None. pop returns an owned value and keeps no borrow of stack, so the body may push; a for loop over &stack borrows it for the whole loop.

solid answer

~50 s

`while let PATTERN = EXPR { body }` is shorthand for a `loop` that evaluates `EXPR`, runs the body if it matches `PATTERN` and breaks otherwise. With `stack.pop()` the expression is re-evaluated each time round, so the loop keeps going while elements remain and stops on the first `None`; that makes it the idiom for a depth-first work list. `pop` takes `&mut self` only for the call and returns an owned `Option<T>`, so by the time the body runs nothing borrows `stack` and `stack.push(child)` is fine. A `for n in &stack` loop is different: its iterator borrows the vector for the whole loop, and pushing inside it is E0502. Its single-pattern sibling `if let Some(x) = opt { ... } else { ... }` runs one branch, with `x` visible only in the first block.

code

rust · 20 lines
rust
use std::collections::HashMap;

fn main() {
    let deps: HashMap<&str, Vec<&str>> = HashMap::from([
        ("app", vec!["http", "log"]),
        ("http", vec!["tls"]),
    ]);
    let mut stack = vec!["app"];
    let mut order = Vec::new();
    // `pop()` returns an owned Option<&str>; the loop ends on None.
    while let Some(name) = stack.pop() {
        order.push(name);
        if let Some(children) = deps.get(name) {
            stack.extend(children); // allowed: the scrutinee holds no borrow of `stack`
        } else {
            println!("{name} is a leaf");
        }
    }
    println!("{order:?}");
}

go deeper

for a junior

Write while let Some(x) = stack.pop() from memory and say it stops at None; use if let for a single Option check.

for a middle

Explain the desugaring to loop plus match, why the scrutinee is re-evaluated, and why pushing in the body compiles while the same push inside for over &stack is E0502.

for a senior

Spot loops whose scrutinee never changes, pick pop or pop_front for depth-first or breadth-first work lists, and keep bindings scoped correctly.

for a principal

Prefer work-list loops whose progress is visible in the condition, so reviewers can see how each loop terminates without tracing flags.

## `if let`: test one pattern once `if let PATTERN = EXPR { ... } else { ... }` runs the first block when `EXPR` matches `PATTERN`, binding the pattern's variables for that block, and runs the optional `else` otherwise. It is the short form of a two-arm `match` whose second arm is `_`, and it is the right tool when only one shape matters: ```rust if let Some(children) = deps.get(name) { stack.extend(children); } else { println!("{name} is a leaf"); } ``` Three rules come with it: - **The bindings live only in the first block.** `children` is not visible in the `else` block or after the `if let`; using it there is E0425, *cannot find value*. - **The pattern should be refutable.** `if let y = x` always matches, and rustc warns with `irrefutable_let_patterns`: *irrefutable `if let` pattern*. - **`if let` is an expression** like `if`: with an `else` whose type matches, it can produce a value. The material on `match` covers exhaustive matching over many variants; `if let` deliberately ignores the rest. ## `while let`: repeat until the pattern fails The Reference defines `while let` by a desugaring: ```plaintext 'label: loop { match EXPR { PATS => { /* loop body */ }, _ => break, } } ``` Two consequences follow: 1. **The scrutinee is evaluated again before every iteration.** With `stack.pop()` that is what you want: each call removes one element, and the loop ends when `pop` returns `None`. 2. **A `while let` loop evaluates to `()`**, like `while`, so it cannot end with a valued `break` (E0571). The pattern may use `|`: `while let Some(v @ 1) | Some(v @ 2) = vals.pop()` is valid and stops at the first value that is neither. ## Why the body may change the collection The borrow checker sees `stack.pop()` as a short `&mut stack` borrow that ends when `pop` returns. The result, `Option<&str>` here, is owned by the pattern, not borrowed from `stack`, so inside the body `stack` is free again and `stack.extend(children)` or `stack.push(x)` compiles. A `for` loop over a reference behaves differently. `for n in &stack` creates an iterator that borrows `stack` immutably until the loop ends, so `stack.push(...)` inside it is: ```plaintext error[E0502]: cannot borrow `stack` as mutable because it is also borrowed as immutable ``` rustc 1.99 even labels the loop: *this for loop borrows `stack` immutably, preventing mutation within its body*. Borrow-checker errors in general belong to the ownership material; here the point is that `while let` over `pop` is the loop shape that lets a work list grow while you drain it. | Loop | Scrutinee re-evaluated? | Body may push onto `stack`? | Stops when | |---|---|---|---| | `while let Some(x) = stack.pop()` | yes, each iteration | yes | `pop` returns `None` | | `for x in &stack` | no, one iterator | no: E0502 | the iterator is exhausted | | `while !stack.is_empty() { let x = stack.pop().unwrap(); }` | yes | yes | the condition is false | The third form works but repeats the emptiness test and adds an `unwrap` that the pattern makes unnecessary. ## Pitfalls - **A scrutinee that never changes loops forever.** `let job = Some(1); while let Some(n) = job { ... }` re-tests the same `Some(1)` each time. Use `if let` for one test, or `job.take()`, which leaves `None` behind. - **Other shapes follow the same rule:** `VecDeque::pop_front` for a breadth-first queue, `iter.next()` on an iterator you advance by hand. Each call must make progress toward the pattern failing. - **A 2024 let chain in a `while` ends the loop at the first operand that fails**, not just that iteration; the let-chain material covers the details. ## Choosing the construct - One optional value, act only when present: `if let`. - One optional value, act on both outcomes: `if let ... else`, or `let`-`else` when the miss path leaves the function. - Repeat while a call keeps producing a matching value: `while let`. - Walk a collection you do not change: `for`. - Many variants, each handled differently: `match`.

  • What does `let job = Some(1); while let Some(n) = job { println!("{n}"); }` do in Rust?
    It prints `1` forever. `while let` re-evaluates `job` before each iteration, and nothing changes it, so the pattern keeps matching. Use `if let` for a single test, or `while let Some(n) = job.take()`, since `take` replaces the value with `None`.
  • In Rust, where can the binding from `if let Some(user) = lookup(id) { ... } else { ... }` be used?
    Only inside the first block. It is not in scope in the `else` block, which runs precisely because there was no `user`, nor after the statement; rustc reports E0425 there. When the value is needed for the rest of the function, use `let Some(user) = lookup(id) else { return ... };`.
  • Can a Rust `while let` loop end with `break value`?
    No. Like `while`, it can end because its pattern stops matching, with no value to give, so it always evaluates to `()` and a valued `break` is E0571, reported as *`break` with value from a `while` loop*. Use `loop` with a `match` or `let`-`else` inside when you need a value.

  • while let evaluates its expression once and then iterates over the result
  • you cannot push onto a Vec while a while let loop is popping from it
  • the binding from if let stays in scope after the if let statement
  • a for loop over &stack may push onto stack because the loop only reads
  • while let Some(n) = job ends after one pass even if job never changes