Sub topic 5
Repeating with loop and while
This chapter covers Rust's two general-purpose repetition constructs, loop and while. It assumes you can build and run a program with cargo, know the primitive types, and understand let and let mut. The for loop, loop labels, and break with a value get their own chapters. Here we focus on the working model of loop and while, and on the mistakes that come up most often.
The working model
Rust has three loop forms: loop, while, and for. They differ in how they decide when to stop.
| Construct | Stops when | Typical use |
|---|---|---|
| `loop` | You write `break` or `return` | Retry logic, event loops, "run until something happens" |
| `while condition` | The condition evaluates to `false` | Repeat while a state holds |
| `for pattern in iterator` | The iterator is exhausted | Walk a range or collection (next chapter) |
All three are expressions. while and for always evaluate to the unit value (). loop can evaluate to another type, because break can carry a value (covered in a later chapter).
Unconditional repetition with loop
loop repeats its body forever until control leaves it. It has no condition.
fn main() {
let mut count = 0;
loop {
count += 1;
println!("pass {count}");
if count == 3 {
break;
}
}
println!("done after {count} passes");
}This prints pass 1, pass 2, pass 3, and then done after 3 passes.
The body is a block, so it needs braces. There are three ways out of a loop:
breakexits the loop and continues after it.returnexits the whole function.- A
panic!, a call tostd::process::exit, or any other diverging call ends the program or unwinds the stack.
continue
continue skips the rest of the current pass and starts the next one. In a loop you must make sure the state that ends the loop still changes before you continue. Otherwise you create an infinite loop.
fn main() {
let mut n = 0;
loop {
n += 1;
if n % 2 == 0 {
continue;
}
println!("odd: {n}");
if n >= 7 {
break;
}
}
}The increment comes before the continue. If it came after, an even n would continue forever without changing.
Conditional repetition with while
while checks a boolean condition before every pass. If the condition is false on the first check, the body never runs.
fn main() {
let mut n = 27u64;
let mut steps = 0;
while n != 1 {
n = if n % 2 == 0 { n / 2 } else { 3 * n + 1 };
steps += 1;
}
println!("reached 1 in {steps} steps");
}The condition must be exactly bool. Rust does not treat integers or other values as truthy or falsy. while n { fails to compile when n is an integer, and you must write while n != 0 {. Parentheses around the condition are allowed but unnecessary, and the compiler warns about them.
while and break/continue work together as you would expect:
fn main() {
let mut x = 100;
while x > 0 {
x -= 7;
if x % 5 == 0 {
println!("hit a multiple of 5: {x}");
break;
}
}
}Choosing between loop and while
A while loop is a loop with the condition moved to the top. These two are equivalent:
fn main() {
let mut a = 3;
while a > 0 {
a -= 1;
}
let mut b = 3;
loop {
if b <= 0 {
break;
}
b -= 1;
}
println!("{a} {b}");
}Use while when the stop condition is a single check you can state at the top. Use loop when the exit happens in the middle of the body, when there are several exits, or when the loop should never end by itself, as in a server's main loop.
A worked example: retrying an operation
Retrying is a good fit for loop, because the exit depends on the result of work done inside the body.
fn flaky(attempt: u32) -> Result<String, String> {
if attempt < 3 {
Err(format!("attempt {attempt} failed"))
} else {
Ok(format!("attempt {attempt} succeeded"))
}
}
fn main() {
let max_attempts = 5;
let mut attempt = 0;
loop {
attempt += 1;
match flaky(attempt) {
Ok(msg) => {
println!("{msg}");
break;
}
Err(e) if attempt < max_attempts => {
println!("{e}, retrying");
continue;
}
Err(e) => {
println!("giving up: {e}");
break;
}
}
}
}Three exits are handled in one place: success, a failure with attempts left, and a failure with none left. A while attempt < max_attempts loop would need extra logic after it to tell success from exhaustion.
Here is the control flow as a diagram.
Edge cases and common errors
Loops that never end
A loop without a reachable break or return runs forever. The compiler accepts this. It is legal, and it has type ! (the never type), which a later chapter covers. For while, the compiler does not analyze your condition, so while true is accepted but triggers a lint suggesting loop. Prefer loop because the compiler then knows the loop only exits through break or return.
fn forever() -> u32 {
let mut n = 0;
loop {
n += 1;
if n == 10 {
return n;
}
}
}
fn main() {
println!("{}", forever());
}This function has no statement after the loop, and it still compiles with a u32 return type. The only exit is return, so the compiler knows no path falls off the end. With while true in the same position, the compiler would not accept the function, because it treats while as something that may finish and produce ().
Forgetting to update the condition
The most common while bug is a condition that never changes.
fn main() {
let limit = 3;
let mut i = 0;
while i < limit {
println!("i = {i}");
i += 1; // remove this line and the loop never ends
}
}When a program hangs, check that every variable in the while condition changes on every path through the body, including paths that use continue.
Unsigned underflow
Counting down with an unsigned integer and the condition >= 0 is always true, because an unsigned value cannot be negative.
fn main() {
let mut n: u32 = 3;
while n > 0 {
println!("{n}");
n -= 1;
}
println!("liftoff");
}Using n > 0 avoids the problem. If you wrote while n >= 0, then n -= 1 at zero would panic in a debug build with "attempt to subtract with overflow". In a release build, it wraps to u32::MAX by default and the loop keeps going. The compiler also warns that the comparison is useless.
Mutating what you iterate
A while loop that indexes into a vector must keep the index in range.
fn main() {
let items = vec![10, 20, 30];
let mut i = 0;
while i < items.len() {
println!("{}", items[i]);
i += 1;
}
}This works, but it is the style for item in &items replaces. Manual indexing carries bounds checks at runtime and gives you the chance to get the bound wrong. Reserve index-based while loops for cases where the index moves in an irregular way, such as a parser that advances by a variable amount.
Shadowing and scope inside loops
Variables declared inside the body are created fresh on every pass and dropped at the end of it. State you want to keep across passes must be declared before the loop, with let mut if it changes.
fn main() {
let mut total = 0;
let mut pass = 0;
while pass < 3 {
let step = pass * 10; // new binding each pass
total += step;
pass += 1;
}
println!("{total}");
}The loop is an expression of type ()
Because while yields (), you cannot write let r = while ... { break 5; };. Rust rejects break with a value inside while and for. Only loop allows it. If you need a result from a conditional loop, store it in a let mut variable declared before the loop, or switch to loop.
Choosing a construct
- If you are walking a range or a collection, use
for. - If the loop ends on a single condition checked at the top, use
while. - If the loop has exits in the middle, several exits, or no natural end, use
loop. - If you need a value out of the loop, use
loopwithbreak value.
Exercise
What does this program print, and why does it stop? fn main() { let mut n = 10; loop { n -= 3; if n < 0 { break; } if n % 2 == 0 { continue; } println!("{n}"); } }
Show answer
It prints 7 and 1. The values of n after each subtraction are 7, 4, 1, and -2. 7 is odd, so it prints. 4 is even, so continue skips the print. 1 is odd, so it prints. -2 is negative, so break ends the loop. The decrement runs before every continue, so the loop always makes progress.
Exercise
Rewrite this function using loop instead of while true, and explain why the original does not compile. fn firstsquareover(limit: u32) -> u32 { let mut n = 0; while true { n += 1; if n * n > limit { return n; } } }
Show answer
Write loop { n += 1; if n * n > limit { return n; } } in place of the while true block. The original fails because the compiler treats while as a construct that might finish and evaluate to (), so it sees a path that reaches the end of the function without returning a u32. A loop has no such path, because its only exits are break and return, and here there is only the return.