Rust — While Loops
Three kinds of loops
while condition { … } // repeat while true
loop { … } // forever (until break)
for x in collection { … } // iterate everything
while — condition-driven
let mut count = 3;
while count > 0 {
println!("{}", count);
count -= 1;
}
println!("Liftoff!");
Condition checked before each pass; the mut counter must march toward false or you hang the program.
loop + break = a value-producing infinite loop
Rust's loop is deliberate "run until told otherwise" — and it can RETURN a value via break:
let mut attempts = 0;
let result = loop {
attempts += 1;
if attempts * attempts > 50 {
break attempts; // ← loop evaluates to this
}
};
println!("stopped at {}", result); // 8
break value; makes the whole loop expression evaluate. Only bare loop can do this (while/for always return ()).
The canonical use: retry logic
let connection = loop {
match try_connect() {
Ok(conn) => break conn, // success → exit WITH the connection
Err(_) => continue, // retry
}
};
break / continue
let mut i = 0;
while i < 10 {
i += 1;
if i % 2 == 0 { continue; } // skip evens
if i > 7 { break; } // stop past 7
println!("{}", i);
}
// prints 1, 3, 5, 7
Labeled loops — breaking nested ones
break exits only the innermost loop. Labels target outer ones:
'outer: for row in grid {
for cell in row {
if cell == TARGET {
break 'outer; // exits BOTH loops
}
}
}
Labels start with an apostrophe. Same syntax works for continue 'outer.
while vs for vs loop
| Situation | Pick |
|---|---|
| Visit every item of a collection | for (always safer) |
| Repeat exact count | for … in range |
| Condition may never become false / retry pattern | while |
| Need the exit VALUE / intentional infinite | loop |
Rule of thumb: if you're writing
while i < list.len(), stop — that's whatforis for. Reach forwhileonly when no collection exists to iterate.
Gotchas: forgetting the counter update (infinite) · using
whileover a Vec when aforwould avoid index-out-of-bounds risks entirely.
Mini Practice
- Countdown 10→0 with while.
- Digit-sum of a number using
% 10and/ 10. - loop+break returning first square above 500.
- Menu loop reading input until "quit".
- Nested grid search breaking both loops with a label.
Next: for loops →
Related Topics
Frequently Asked Questions about While Loops
What is While Loops in Rust?
While Loops is a fundamental concept in Rust. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn While Loops?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn While Loops.
Why is While Loops important in Rust?
While Loops is essential for Rust development. Understanding this concept will help you write better code and solve real-world problems more effectively.