Rust Reference ยท Keywords and Statements
The while loop
Reference for Rust while loops: running while a condition holds, while let for patterns and stacks, labels, let chains and why while true is discouraged.
while evaluates a boolean condition before each iteration and runs the body as long as it is true. If the condition is false the first time, the body never runs. The loop itself always has the type (), so it cannot produce a value; use loop with break value for that.
while let is the pattern-based sibling: it keeps looping while a pattern matches. It is the idiomatic way to drain a stack, read from an iterator or channel by hand, or walk a linked structure until the pointer runs out.
while n > 0 { n -= 1; } while let Some(top) = stack.pop() { println!("{top}"); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
while condition { body } while let PATTERN = expression { body } 'label: while condition { ... break 'label; ... }
| Part | Description |
|---|---|
condition |
Must be of type bool. It is re-evaluated before every iteration. |
PATTERN = expression |
The expression is re-evaluated every iteration; the loop stops at the first time the pattern fails to match. |
break, continue |
Leave the loop or skip to the next check. break cannot carry a value here. |
Type: the whole loop evaluates to (). Writing break 5; inside while is error E0571.
Usage notes
- Use
forwhen iterating a collection or a range. It cannot go out of bounds and is usually as fast;while i < v.len()with manual indexing is easy to get wrong. while trueis flagged by a lint (while_true); writeloopinstead, which also tells the compiler the loop only ends viabreak.- Mutating the condition inside the body is the whole point, so make sure something changes or the loop never ends.
while letonpop()drains the collection in last-in, first-out order. For a queue, useVecDeque::pop_front.- Borrow trap:
while let Some(x) = iter.next()lets you useiterinside the body, whichfor x in iterdoes not. - Lock guards: a temporary in the
while letscrutinee, such aswhile let Some(job) = queue.lock().unwrap().pop(), keeps the lock for the whole body. Take the value into a localletfirst when the body is slow. - Let chains (
while let ... && cond) need edition 2024 and Rust 1.88 or later. - Floating-point conditions such as
while x != 1.0can loop forever because of rounding; compare with a tolerance.
Related
loop,for,breakandcontinue,ifandelse, if let, while let and let-else- Lessons: Loops, Patterns