The while Loop
The while loop runs as long as a condition is true .
Example
let mut count = 1;
while count <= 5 {
println!("Count: {}", count);
count += 1;
}In the example above, the loop keeps running as long as the counter is less than or equal to 5.
It prints the numbers from 1 to 5, one on each line.
False Condition
The while loop checks the condition before each loop, so if the condition is false at the start, the loop will not run at all:
Example
let count = 10;
while count <= 5 {
println!("This won't be printed.");
}Stop a While Loop
You can stop a while loop when you want by using break :
Example
let mut num = 1;
while num <= 10 {
if num == 6 {
break;
}
println!("Number: {}", num);
num += 1;
}This prints numbers from 1 to 5 (stops the loop when num reaches 6).
Skip a Value
You can skip a value by using the continue statement:
Example
let mut num = 1;
while num <= 10 {
if num == 6 {
num += 1;
continue;
}
println!("Number: {}", num);
num += 1;
}This prints numbers from 1 to 10, except for the number 6.