While Let Pops Items Until Empty
Drain a stack with while let Some(item) = stack.pop(), the pattern-matching loop that exits only when the Option turns None.
Code
fn main() {
let mut backlog = vec!["lint", "test", "build", "ship"];
// while let:每次弹出栈顶,直到 Option 变成 None 才退出
while let Some(task) = backlog.pop() {
println!("running {task}");
}
println!("backlog empty: {}", backlog.is_empty());
// take() 取走当前值并把 Option 置回 None,同样适合 while let
let mut current = Some("deploy");
while let Some(stage) = current.take() {
println!("stage {stage}");
current = if stage == "deploy" { Some("verify") } else { None };
}
}What the code does
While Let Pops Items Until Empty comes down to the function main.
Repetition is confined to while let Some(task) = backlog.pop() — the rest of the file is straight-line.
Using it
Running the file prints labeled results such as running, backlog empty:, stage — each operation’s effect is visible in the output.
Key statements
while let Some(stage) = current.take() {
println!("stage {stage}");
current = if stage == "deploy" { Some("verify") } else { None };
}
while let Some(task) = backlog.pop() {
println!("running {task}");
}
let mut current = Some("deploy");
Interactive Tools for This Topic
FAQ
- What does While Let Pops Items Until Empty print when run?
- Running the file directly is enough — expect labeled output lines such as `running`, `backlog empty:`, `stage`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.