src/pattern-matching/let-control-flow/while-let.md
while let StatementsLike with if let, there is a
while let
variant that repeatedly tests a value against a pattern:
# // Copyright 2025 Google LLC
# // SPDX-License-Identifier: Apache-2.0
#
fn main() {
let mut name = String::from("Comprehensive Rust 🦀");
while let Some(c) = name.pop() {
dbg!(c);
}
// (There are more efficient ways to reverse a string!)
}
Here
String::pop
returns Some(c) until the string is empty, after which it will return None.
The while let lets us keep iterating through all items.
while let loop will keep going as long as the value
matches the pattern.while let loop as an infinite loop with an if
statement that breaks when there is no value to unwrap for name.pop(). The
while let provides syntactic sugar for the above scenario.