Chapter 14: Rust Loops
Rust Loops.
Loops are how we tell the computer: “Hey, repeat this block of code many times — until something tells you to stop!” Rust gives you three main loop kinds, each with its own personality:
- loop → infinite until you break (very explicit & safe)
- while → repeat while a condition is true
- for → repeat over something (ranges, arrays, vectors, iterators — Rust’s favorite!)
Rust makes loops very safe — no accidental infinite loops without break, labels for nested loops, and iterators that prevent many bugs.
Let me explain like your teacher sitting next to you with a laptop: slowly, with tons of copy-paste examples (run them with cargo run), Hyderabad-flavored comments, and step-by-step from simple to advanced.
1. The loop Keyword — Infinite Until You Say Stop
loop { … } = runs forever unless you break
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
fn main() { let mut count = 0; loop { count += 1; println!("Counting: {}", count); if count == 5 { println!("OK, that's enough! Stopping now 🛑"); break; // exit the loop } } } |
- break → immediately exit the loop
- continue → skip rest of this iteration, go to next
Classic example with continue:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
fn main() { let mut number = 0; loop { number += 1; if number % 2 == 0 { println!("Skipping even number: {}", number); continue; // jump back to loop start } println!("Odd number: {}", number); if number >= 9 { break; } } } |
Output: only odd numbers 1,3,5,7,9
2. while Loop — Repeat While Condition is True
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
fn main() { let mut temperature = 28; while temperature < 35 { println!("Temperature now: {}°C — still comfortable ☀️", temperature); temperature += 2; // Hyderabad summer heating up! } println!("Now {}°C — AC time! ❄️", temperature); } |
- Condition checked before each iteration
- If false at start → loop body never runs
3. for Loop — Rust’s Most Loved Loop (Iterators!)
for works beautifully with ranges and collections.
A. For with Range (.. or ..=)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
fn main() { // 1 to 5 (exclusive end) for i in 1..6 { println!("Day {} of learning Rust!", i); } println!("---"); // 1 to 5 inclusive for i in 1..=5 { println!("Inclusive count: {}", i); } } |
- 1..6 = 1,2,3,4,5
- 1..=5 = 1,2,3,4,5
B. For over Arrays / Slices
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
fn main() { let weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]; for day in weekdays { println!("Today is {} — time to code! 🦀", day); } // With index (very common) for (index, day) in weekdays.iter().enumerate() { println!("Day {}: {}", index + 1, day); } } |
C. For over Vectors (growable arrays)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
fn main() { let mut biryani_spice_levels = vec![3, 5, 8, 10]; // out of 10 for level in &biryani_spice_levels { println!("Spice level: {} 🔥", level); } // Modify while iterating (use mut &) for level in &mut biryani_spice_levels { *level += 2; // make it spicier! } println!("After extra mirchi: {:?}", biryani_spice_levels); } |
4. Loop Labels — For Nested Loops (Break/Continue Specific One)
|
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 28 29 |
fn main() { 'outer: loop { // label 'outer println!("Entered outer loop"); let mut inner_count = 0; loop { println!(" Inner loop count: {}", inner_count); inner_count += 1; if inner_count == 3 { println!(" Breaking inner loop"); break; // only inner } if inner_count == 5 { println!("Breaking BOTH loops!"); break 'outer; // exit outer too } } } println!("Exited all loops!"); } |
- Labels: ‘name: (apostrophe + identifier)
- break ‘label or continue ‘label
5. Returning Values from Loops (Expression Style)
loop (and sometimes while) can return a value with break value;
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
fn main() { let mut counter = 0; let result = loop { counter += 1; if counter == 10 { break counter * 2; // return this value from loop } }; println!("Loop finished — result is {}", result); // 20 } |
Quick Summary Table (Teacher Style)
| Loop Type | When to Use | Syntax Example | Key Features |
|---|---|---|---|
| loop | Infinite until explicit break | loop { if cond { break; } } | break, continue, labels, return value |
| while | Repeat while condition true | while x < 10 { x += 1; } | Condition at top, simple counters |
| for | Iterate over range/collection/iterator | for i in 1..=10 { … } | Safest & cleanest, no off-by-one bugs |
Practice Tips
- Create cargo new rust_loops
- Try counting from 1 to 100 with all three kinds
- Make a FizzBuzz with for 1..=100
- Nested loop printing a small pattern (stars or Hyderabad map 😄)
- Use break with value to find first number divisible by 7 and 11
Rust loops feel very clean once you get used to for over iterators — most real Rust code uses for 70–80% of the time.
Next topic?
- Functions (how loops live inside them)?
- Ownership & borrowing with loops (very important!)?
- Or iterators in depth (.iter(), .map(), .filter())?
Just tell me — your Rust teacher from Telangana is ready! 🦀🚀
