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.
Basic while loop
Section titled “Basic while loop”fn main() { let mut count = 1;
while count <= 5 { println!("{count}"); count += 1; }}Output:
12345The 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.
while vs loop
Section titled “while vs loop”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 pointlet mut n = 0;while n < 3 { println!("{n}"); n += 1;}
// the same thing with loop — works, but more to readlet mut n = 0;loop { if n >= 3 { break; } println!("{n}"); n += 1;}A more realistic example
Section titled “A more realistic example”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!");}while condition { ... }repeats as long as the condition istrue, checked before each run.- Make sure something inside the loop eventually makes the condition
false, or it’ll run forever. - Prefer
whileoverloopwhenever the stopping condition fits naturally as “while X holds.”
Quick check
Section titled “Quick check”Quick check
1. What's the classic mistake that causes an infinite `while` loop?
2. When should you prefer `while` over `loop`, per this page?
Score: 0 / 2