Skip to content

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.

fn main() {
let mut count = 0;
loop {
count += 1;
println!("{count}");
if count == 3 {
break;
}
}
}

Output:

1
2
3
▶ Try it Yourself

loop on its own never stops — break is what ends it. Without that if count == 3 { break; }, this program would print forever.

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:

20
▶ Try it Yourself

This 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.

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.

  • loop repeats forever until a break stops it — always make sure one exists.
  • break value; stops the loop and returns value as the result of the whole loop expression.
  • Reach for loop when you’re repeating “until some condition happens,” not when counting a known number of times.

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