Skip to content

Rust While

A while loop keeps running as long as a condition stays true. It’s the right tool when you know what you’re waiting for, even if you don’t know exactly how many times it’ll take.

fn main() {
let mut count = 1;
while count <= 5 {
println!("{count}");
count += 1;
}
}

Output:

1
2
3
4
5
▶ Try it Yourself

The condition (count <= 5) is checked before every run through the loop. As soon as it’s false, the loop ends — here, after count becomes 6.

You could write the same thing with loop and a manual if/break, but while says what you mean more directly: “keep going while this is true.” Save loop for cases where the stopping condition doesn’t fit naturally at the top of the loop.

// with while — clear and to the point
let mut n = 0;
while n < 3 {
println!("{n}");
n += 1;
}
// the same thing with loop — works, but more to read
let mut n = 0;
loop {
if n >= 3 {
break;
}
println!("{n}");
n += 1;
}

while is common for things like waiting for a value to reach a target:

fn main() {
let mut balance = 100;
while balance < 200 {
balance += 25;
println!("Balance is now {balance}");
}
println!("Reached the goal!");
}
▶ Try it Yourself
  • while condition { ... } repeats as long as the condition is true, checked before each run.
  • Make sure something inside the loop eventually makes the condition false, or it’ll run forever.
  • Prefer while over loop whenever the stopping condition fits naturally as “while X holds.”