while let in Rust
while let keeps looping as long as the pattern matches — draining a stack, say.
fn main() {
let mut stack = vec![1, 2, 3, 4];
while let Some(top) = stack.pop() {
println!("popped {top}");
}
let mut chars = "abc".chars();
while let Some(c) = chars.next() {
print!("[{c}]");
}
println!();
}
How it works
popyieldsSomeuntil the vector is empty.- The loop ends when the pattern stops matching.
- It replaces a
loopwith amatchand abreak.
Keywords and builtins used here
Somefnletmainmutwhile
The run, in numbers
- Lines
- 12
- Characters to type
- 209
- Tokens
- 79
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 56 seconds.
Step 5 of 8 in Control flow, step 15 of 39 in Language basics.