Take Control of Your Loops!
Loops are great, but sometimes you just need to exit early (break
) or skip an iteration (continue
). Rust gives you the power to control your loops like a pro! Let’s dive into it.
1. Breaking Out of a Loop with break
The break
statement immediately stops the loop and jumps to the next statement after it.
a) Basic break
Example
fn main() {
let mut count = 0;
loop {
println!("Count: {}", count);
count += 1;
if count == 5 {
println!("Stopping loop!");
break;
}
}
}
The loop stops when count
reaches 5. No infinite loops—unless you forget break
!
b) break
in a while
Loop
fn main() {
let mut num = 1;
while num < 10 {
if num == 6 {
println!("We hit 6! Breaking out!");
break;
}
println!("Number: {}", num);
num += 1;
}
}
Great for stopping early based on conditions.
2. Skipping an Iteration with continue
The continue
statement skips the current iteration and moves to the next one.
a) Using continue
in a for
Loop
fn main() {
for num in 1..=5 {
if num == 3 {
println!("Skipping 3!");
continue;
}
println!("Number: {}", num);
}
}
The number 3
is skipped, but the loop keeps going.
b) continue
in a while
Loop
fn main() {
let mut num = 0;
while num < 5 {
num += 1;
if num % 2 == 0 {
println!("Skipping even number: {}", num);
continue;
}
println!("Odd number: {}", num);
}
}
Skips even numbers, only prints odd numbers.
Wrapping Up
Now you’ve mastered: break
to exit loops early. continue
to skip specific iterations. Using them in for
, while
, and loop
structures.
0 Comments