Rust Loops
Rust has three ways to repeat code: loop, while, and for. This page covers loop, the simplest and most direct of the three — it repeats forever until you tell it to stop.
A basic loop
Section titled “A basic loop”fn main() { let mut count = 0;
loop { count += 1; println!("{count}");
if count == 3 { break; } }}Output:
123loop on its own never stops — break is what ends it. Without that if count == 3 { break; }, this program would print forever.
Returning a value from a loop
Section titled “Returning a value from a loop”Here’s something loop can do that while and for can’t: you can put a value after break, and that becomes the result of the whole loop:
fn main() { let mut count = 0;
let result = loop { count += 1; if count == 10 { break count * 2; // stop and hand back a value } };
println!("{result}");}Output:
20This is handy for things like “keep retrying until it works, then give me the result” — you’ll see this pattern in real code more than you’d expect.
When to use loop
Section titled “When to use loop”loop is the right choice when you don’t know ahead of time how many times you’ll repeat — you’re waiting for some condition to become true, rather than counting through a range or a list. For counting or iterating over a collection, while and for (covered next) usually read better.
looprepeats forever until abreakstops it — always make sure one exists.break value;stops the loop and returnsvalueas the result of the whole loop expression.- Reach for
loopwhen you’re repeating “until some condition happens,” not when counting a known number of times.
Quick check
Section titled “Quick check”Quick check
1. What stops a bare `loop` from running forever?
2. What does writing `break count * 2;` inside a loop accomplish?
3. When is `loop` the better choice over `while` or `for`, according to this page?
Score: 0 / 3