Sub topic 5
Repeating with loop and while
This chapter assumes you can build and run a program with cargo, know Rust's primitive types, and understand let and let mut. It also assumes you have read the chapters on functions, expressions, and if/else. Rust has three repetition constructs: loop, while, and for. This chapter covers loop and while. The next chapter covers for.
The loop expression
loop repeats its body until something stops it. It has no condition. You stop it with break, with return, or by ending the program.
fn main() {
let mut count = 0;
loop {
count += 1;
println!("count = {count}");
if count == 3 {
break;
}
}
println!("done");
}Use loop when the exit point sits in the middle of the body, or when the loop must run at least once. Examples are retrying an operation or reading input until it is valid. The compiler knows loop runs at least once. It also knows that code after a loop without a break is unreachable.
Returning a value with break
loop is an expression, so it can produce a value. Write the value after break.
fn main() {
let mut count = 0;
let first_big = loop {
count += 1;
if count * count > 50 {
break count;
}
};
println!("{first_big}");
}This prints 8, because 8 × 8 = 64 is the first square above 50. The loop is the right side of a let, so it ends with a semicolon. Every break in the loop must carry a value of the same type. A bare break; gives the loop the type ().
Only loop can break with a value. A while or for loop may finish without ever hitting a break. It has no value to produce, so its type is always ().
The while loop
while checks a condition before each pass. If the condition is false at the start, the body never runs.
fn main() {
let mut n = 5;
while n > 0 {
println!("{n}");
n -= 1;
}
println!("liftoff");
}The condition must be a bool. Rust does not treat 0 or an empty string as false.
Choosing between them
| Situation | Use |
|---|---|
| Condition is known before the first pass | `while` |
| Exit depends on work done inside the body | `loop` |
| You need to return a value from the loop | `loop` |
| You walk a fixed range or a collection | `for` (next chapter) |
Using continue
continue skips the rest of the current pass and goes back to the top. For while, that means checking the condition again.
fn main() {
let mut n = 0;
while n < 10 {
n += 1;
if n % 2 == 0 {
continue;
}
println!("{n}");
}
}This prints the odd numbers from 1 to 9. Update the counter before continue. If you put n += 1 after the if, the even branch would skip it and the program would loop forever.
Common errors
- Infinite
while. If nothing in the body changes the condition, the loop never ends. Check that the variable in the condition is updated on every path, including paths that usecontinue. - Forgetting
mut. A counter that changes needslet mut. The compiler reports an error for assigning twice to an immutable variable. - Mismatched break types.
break 1;in one place andbreak "x";in another gives a type error, because the loop has one type. - Using
while true. It compiles, but the compiler cannot treat it as a loop that never exits normally. Writeloopinstead. It makes your intent clear and lets the compiler reason about it. - Index-based
whileover a collection. Counting up tov.len()works, but it invites off-by-one mistakes. Preferfor.
Exercise
What does this program print, and why does it compile? let x = loop { break 7; }; println!("{}", x + 1);
Show answer
It prints 8. A loop is an expression, and break 7 gives it the value 7 with type i32. The variable x holds that value, so x + 1 is 8.
Exercise
Write a while loop that halves a u32 variable n, starting at 100, until it is 1 or less, and counts the halvings in a variable steps. What are n and steps at the end?
Show answer
let mut n: u32 = 100; let mut steps = 0; while n > 1 { n /= 2; steps += 1; }. The values go 100, 50, 25, 12, 6, 3, 1, so n is 1 and steps is 6.