🔄 Rust Loops: The Merry-Go-Round of Code
The Big Idea
Imagine you’re on a merry-go-round at a playground. Round and round you go! Sometimes you spin forever until someone stops you. Sometimes you spin only while the music plays. Sometimes you spin exactly 5 times and then hop off.
Loops in Rust work exactly like this! They let your code do something over and over again.
🎠 The loop Keyword: The Infinite Merry-Go-Round
The loop is like a merry-go-round that never stops on its own. It just keeps going and going!
loop {
println!("Wheee!");
// This prints forever!
}
Why use it? Sometimes you need your program to keep running until YOU decide to stop it. Like a game that keeps playing until you press “quit”.
🎵 while Loops: Spin While the Music Plays
A while loop is like spinning on the merry-go-round while the music is playing. The moment the music stops? You stop too!
let mut music_playing = true;
let mut spins = 0;
while music_playing {
println!("Spinning!");
spins += 1;
if spins >= 3 {
music_playing = false;
}
}
// Output: Spinning! (3 times)
The rule: Keep going while something is true. Stop when it becomes false.
🎯 for Loops: Exactly 5 Rides, No More!
A for loop is like buying a ticket for exactly 5 rides. You know exactly how many times you’ll go around!
for ride in 1..=5 {
println!("Ride number {}!", ride);
}
// Output: Ride 1, 2, 3, 4, 5
The rule: Go through each item in a collection, one by one, until you’ve seen them all.
📏 Range Expressions: Counting Your Rides
Ranges are like numbered tickets that say “from here to there.”
The Two Types
| Range | What It Means | Example |
|---|---|---|
1..5 |
1, 2, 3, 4 (stops BEFORE 5) | Like “up to but not including” |
1..=5 |
1, 2, 3, 4, 5 (includes 5) | Like “from 1 through 5” |
// Exclusive range (..): 1 to 4
for i in 1..5 {
print!("{} ", i);
}
// Output: 1 2 3 4
// Inclusive range (..=): 1 to 5
for i in 1..=5 {
print!("{} ", i);
}
// Output: 1 2 3 4 5
Memory trick: The = sign means “equals too” — include that last number!
🛑 break: Jump Off the Ride!
Sometimes you want to jump off the merry-go-round early. That’s what break does!
loop {
println!("Spinning...");
break; // STOP! Get off now!
}
println!("I'm off the ride!");
Real example: Finding something
let numbers = [1, 2, 3, 7, 5];
for num in numbers {
if num == 7 {
println!("Found lucky 7!");
break; // Stop looking!
}
}
⏭️ continue: Skip This Turn!
What if one seat on the merry-go-round is wet? You skip it and wait for the next one! That’s continue.
for seat in 1..=5 {
if seat == 3 {
println!("Seat 3 is wet! Skip!");
continue; // Skip to next seat
}
println!("Sitting on seat {}", seat);
}
Output:
Sitting on seat 1
Sitting on seat 2
Seat 3 is wet! Skip!
Sitting on seat 4
Sitting on seat 5
🏷️ Loop Labels: Naming Your Merry-Go-Rounds
What if you have TWO merry-go-rounds, one inside another? How do you tell Rust which one to stop?
Give them names!
'outer: loop {
println!("Outer ride!");
'inner: loop {
println!("Inner ride!");
break 'outer; // Stop the OUTER one!
}
}
println!("Both stopped!");
The label starts with a single quote like 'outer. It’s like giving your merry-go-round a nickname!
graph TD A["Start outer loop"] --> B["Start inner loop"] B --> C{break 'outer} C --> D["Both loops end!"] style C fill:#ff6b6b,color:#fff
🎁 Returning Values from Loops: Win a Prize!
Here’s something magical: Your loop can give you a prize when it stops!
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2; // Return 20!
}
};
println!("My prize: {}", result);
// Output: My prize: 20
How it works:
- Put your loop after
let result = - When you
break, add a value:break 42; - That value becomes your result!
Real example: Keep asking until you get a valid answer
let mut attempts = 0;
let password = loop {
attempts += 1;
let guess = "secret123"; // pretend user input
if guess == "secret123" {
break guess; // Return the password!
}
if attempts >= 3 {
break "LOCKED"; // Too many tries!
}
};
🎯 Quick Comparison
graph TD A["Which loop to use?"] --> B{Know how many times?} B -->|Yes| C["for loop"] B -->|No| D{Have a condition?} D -->|Yes| E["while loop"] D -->|No| F["loop with break"] style C fill:#4ecdc4,color:#fff style E fill:#667eea,color:#fff style F fill:#ff6b6b,color:#fff
| Situation | Use This |
|---|---|
| Loop through a list | for item in list |
| Loop a specific number of times | for i in 0..10 |
| Loop while something is true | while condition |
| Loop forever until break | loop |
| Need to return a value | loop with break value |
🌟 Putting It All Together
Here’s a mini treasure hunt game!
let treasures = [
"rock", "stick", "gold", "leaf"
];
'hunt: for item in treasures {
println!("Found: {}", item);
if item == "gold" {
println!("🎉 TREASURE!");
break 'hunt;
}
}
What happens:
forgoes through each item- We check if it’s gold
- When we find gold,
breakends the hunt!
🚀 You Did It!
Now you know all about Rust loops:
- ✅
loop— spins forever until youbreak - ✅
while— spins while a condition is true - ✅
for— spins through each item in a collection - ✅
..and..=— ranges for counting - ✅
break— jump off early - ✅
continue— skip this turn - ✅ Loop labels — name your loops with
'name: - ✅ Return values — get a prize with
break value
You’re now a Loop Master! 🎠✨
