while let
- Rust course
- Beginner
- Lesson 86/115
- 4 min
Loop while a pattern matches with while let.
while let
while let keeps the loop going as long as the pattern fits. Pulling elements off a stack is the classic example:
let mut yigin = vec![1, 2, 3];
while let Some(ust) = yigin.pop() {
println!("{ust}");
}
// 3, 2, 1 — the loop ends when pop returns NoneThe same code can be written with loop + match + break; while let is its short form.
When to use while let?
If you change the collection during the loop (e.g. pulling elements and adding new ones), you can't use for, because for borrows the collection. while let allows this because it calls pop again each round:
let mut kuyruk = vec![3];
while let Some(n) = kuyruk.pop() {
print!("{n} ");
if n > 1 { kuyruk.push(n - 1); }
}
// 3 2 1Practice Collect from the stack
Declare let mut yigin = vec![1, 2, 3];. With while let Some(x) = yigin.pop(), push ten times each element into a new vector and print the result with {:?}.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let mut yigin = vec![1, 2, 3];
let mut sonuc = Vec::new();
while let Some(x) = yigin.pop() {
sonuc.push(x * 10);
}
println!("{:?}", sonuc);
}Expected output
[30, 20, 10]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which does the same job as <code>while let Some(x) = it.next()</code>?
- loop { it.next(); }
- match it { .. }
- for x in it Correct answer
- if let Some(x) = it.next()
Explanation: A for loop calls next() behind the scenes and continues until None.
2 Empty the stack
while let Some(ust) = yigin.____() {
println!("{ust}");
}
while let Some(ust) = yigin.pop() {
println!("{ust}");
}
Explanation: pop gives the last element inside Some; when empty it returns None and the loop ends.
3 Loop and end condition
| Term | Meaning |
|---|---|
while let Some(x) = v.pop() |
When v is empty |
for x in &v |
When elements run out |
loop |
With break |
while n > 0 |
When the condition is false |