Rust While Loops
A while loop keeps running its body as long as a condition is true. Before each pass, Rust checks the condition; as soon as it becomes false, the loop ends and the program continues after it.
while condition {
// body runs while condition is true
}The condition must be a bool. Unlike some languages, Rust will not treat a number like 0 or 1 as true or false — you have to write the comparison yourself, such as count > 0.
A simple countdown
fn main() {
let mut seconds = 5;
while seconds > 0 {
println!("{}...", seconds);
seconds -= 1;
}
println!("Liftoff!");
}5...
4...
3...
2...
1...
Liftoff!
Each pass prints the current value and subtracts one. When seconds reaches 0, the condition seconds > 0 is false and the loop stops.
Note: The variable you test must be declared with
let mut, otherwise you could not change it inside the loop and the condition would never become false.
When the body never runs
Because the condition is checked before every pass, a while loop may run zero times.
fn main() {
let mut stock = 0;
while stock > 0 {
println!("Selling one item");
stock -= 1;
}
println!("Stock is {}, nothing was sold.", stock);
}Stock is 0, nothing was sold.
Looping until a goal is reached
while shines when you do not know in advance how many steps you need. Here we double a savings balance by adding 10% interest each year and count how many years it takes.
fn main() {
let mut balance = 1000.0;
let target = 2000.0;
let mut years = 0;
while balance < target {
balance *= 1.10;
years += 1;
}
println!("It takes {} years to reach {}.", years, target);
println!("Final balance: {:.2}", balance);
}It takes 8 years to reach 2000.
Final balance: 2143.59
The {:.2} formatter prints the number with exactly two decimal places.
break and continue in while
The same break and continue keywords you met with loop work inside while:
breakleaves the loop immediately, even if the condition is still true.continueskips the rest of this pass and checks the condition again.
fn main() {
let mut n = 0;
while n < 20 {
n += 1;
if n % 2 == 0 {
continue; // skip even numbers
}
if n > 9 {
println!("Passed 9, stopping early.");
break;
}
println!("odd: {}", n);
}
}odd: 1
odd: 3
odd: 5
odd: 7
odd: 9
Passed 9, stopping early.
Tip: Be careful to update the loop variable before a
continue. Ifn += 1were placed after thecontinue, the loop would get stuck on the first even number forever.
while vs loop vs for
| Situation | Best choice |
|---|---|
| Repeat until a condition changes, checked at the start | while |
| Exit point is in the middle, or you need a result value | loop |
| Visit each number in a range or each item in a collection | for |
You can walk through an array with while and an index variable, but a for loop is safer: it cannot accidentally read past the end of the array. You will see for in the next chapter.
Test yourself
When is the condition of a while loop checked?
- Only once, before the first pass
- Before every pass
- After every pass
- Only when
continueis used
Which of these is a valid while condition in Rust if count is an i32?
while count { }while (count) { }while count != 0 { }while count? { }