Chapter 15: Rust While Loops
Rust while loops
The while loop is probably the one that feels most familiar if you’ve programmed in C, Java, Python, JavaScript, etc. It’s very straightforward:
“As long as this condition is true, keep repeating the block.”
Rust’s version is clean, safe, and has almost no surprises — but it also comes with some Rust-specific habits and patterns that make it even more powerful when used correctly.
Let me explain it like your personal teacher sitting next to you: slowly, step by step, with many practical examples you can copy-paste right now, some Hyderabad-flavored comments, and comparisons so you see exactly how it differs from other languages.
1. Basic Syntax of while
|
0 1 2 3 4 5 6 7 8 9 |
while condition { // code that runs repeatedly // usually something changes the condition } |
- Condition must be a bool (no automatic conversion from int like in C!)
- Checked before every iteration
- If condition is false at the very beginning → body never runs (zero times is possible)
Simple first example:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
fn main() { let mut count = 1; while count <= 5 { println!("Namaste! This is loop iteration {}", count); count += 1; // very important — otherwise infinite loop! } println!("Loop finished — we counted to 5 🦀"); } |
Output:
|
0 1 2 3 4 5 6 7 8 9 10 11 |
Namaste! This is loop iteration 1 Namaste! This is loop iteration 2 Namaste! This is loop iteration 3 Namaste! This is loop iteration 4 Namaste! This is loop iteration 5 Loop finished — we counted to 5 🦀 |
Classic teacher warning: Always make sure something inside the loop makes the condition eventually false — otherwise infinite loop (Rust catches many infinite-loop bugs at compile time in other constructs, but while relies on you).
2. Real-world style: Temperature simulation (Hyderabad summer)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
fn main() { let mut temperature = 28; // morning in Feb 2026 let target = 36; // peak afternoon heat println!("Morning temperature: {}°C", temperature); while temperature < target { temperature += 2; println!("Temperature rose to {}°C — getting hotter! ☀️", temperature); } println!("Reached {}°C — full Hyderabad summer mode! 🔥❄️ AC on!", temperature); } |
3. while with user input simulation (common pattern)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
fn main() { let mut guess = 0; let secret = 42; while guess != secret { println!("Guess a number between 1–100 (hint: it's my favorite number)"); // In real program we'd read from stdin — here we simulate increasing guesses guess += 7; // pretend user is guessing 7,14,21,... println!("You guessed: {}", guess); if guess > secret { println!("Too high! Try lower ↓"); } else if guess < secret { println!("Too low! Try higher ↑"); } } println!("Yes! {} is correct — you win 🎉", guess); } |
In real code you would use std::io to actually read input — but this shows the loop logic clearly.
4. while let — The Rust-special version (very common!)
while let combines while + let + pattern matching — super useful with Option, Result, iterators, etc.
Classic example — reading lines until None:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
fn main() { let mut lines = vec![ "Line one", "Line two", "Line three", "" ].into_iter(); // pretend this is reading from file while let Some(line) = lines.next() { if line.is_empty() { println!("Found empty line — stopping"); break; } println!("Read: {}", line); } } |
Even more common with Option:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
fn main() { let mut optional_number = Some(10); while let Some(n) = optional_number { println!("Current value: {}", n); if n == 1 { optional_number = None; // stop condition } else { optional_number = Some(n - 1); } } println!("Countdown finished!"); } |
5. while vs loop — Quick comparison (students always ask)
| Feature | while | loop |
|---|---|---|
| When condition checked | Before body | Never checked automatically |
| Typical use | “repeat while something is true” | “repeat forever until I break” |
| Can return value | No (but can with break in loop) | Yes — break value; |
| Most common in Rust | Less than for | Used when no natural iterator exists |
| Risk of infinite loop | Possible if forget to change var | Very explicit — you must write break |
In real Rust code written 2025–2026:
- for → ~60–70% of loops
- loop → ~20–30%
- while → ~10–15% (mostly while let)
6. Nested while + labels (rare but good to know)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
fn main() { let mut outer = 1; 'outer_loop: while outer <= 3 { println!("Outer: {}", outer); let mut inner = 1; while inner <= 3 { println!(" Inner: {}", inner); if inner == 2 && outer == 2 { println!(" Special condition — breaking both!"); break 'outer_loop; } inner += 1; } outer += 1; } } |
Teacher Summary — When to use while
Use while when:
- You have a clear boolean condition that will become false eventually
- You don’t have a natural collection/range to iterate over (for is usually better then)
- You want to keep checking something until a state changes (file reading, game loops, waiting for condition)
But in modern Rust — prefer for with iterators whenever possible — it’s safer and more idiomatic.
Practice challenge for today:
- Write a while loop that counts down from 10 to 1 (print “Liftoff!” at 0)
- Make a while let version that processes items from a Vec<Option<i32>> until None
- Simulate a simple game loop: keep asking for input until user types “quit”
Want me to show any of these solutions? Or move to for loops in more depth, iterators, functions, or ownership inside loops?
Just tell me — class is still in session! 🦀🚀
