loop + break
Goal of This Episode
Create an infinite loop with loop, then use break to jump out at the right moment.
Main Text
Up to now, our programs run once and end. But what if something needs to be done repeatedly? Like a countdown: 5, 4, 3, 2, 1, liftoff!
That calls for a loop.
loop — the Infinite Loop
loop just keeps running and running, forever:
fn main() {
loop {
println!("I can't stooooop");
}
}
If you actually run this program, it will print and print and print… You’ll have to force-stop it with Ctrl + C.
So we need an “exit.”
break — Jumping Out of the Loop
fn main() {
let mut count = 5;
loop {
if count == 0 {
println!("Liftoff!");
break;
}
println!("{}", count);
count -= 1;
}
}
How Does It Work?
countstarts at 5.- Enter the
loop. First check: iscount == 0? No, so print 5, thencount -= 1makes count 4. - Back to the top of the
loop. Iscount == 0? No, print 4, count becomes 3. - …and so on…
- When
countreaches 0,if count == 0holds: print “Liftoff!”, thenbreakout of the loop. - The program ends.
Recap
looprepeats the code inside the curly braces forever.breakjumps out of the loop so the program can continue on.- A
loopwithout abreakis an infinite loop — remember to have an exit.