With while, we specify an exit condition in the first statement of the loop. And with the "loop" keyword, no exit condition is specified.
While loop. Rust supports the while-keyword, and this is the classic while loop. It continues iterating while the specified condition is true.
Here We start the remaining counter at 10, and decrement it by 2 each pass through the loop. Once it goes negative, we end the loop.
fn main() {
let mut remaining = 10;
// Continue looping while a condition is true.
while remaining >= 0 {
println!("{}", remaining);
// Subtract 2.
remaining -= 2;
}
}10
8
6
4
2
0
Loop keyword. For complex loops with unknown end points, an infinite loop with a condition that tests for the end point is often best. In Rust we can use the "loop" keyword for this.
Tip The loop keyword is like a "while true" loop. It is important to always test for the end condition in the loop body.
Also We should make sure to have a "mut" local variable for the index variable, and increment or decrement it on each iteration.
fn main() {
let mut test = 10;
loop {
// Test for modulo 5.
if test % 5 == 0 {
println!("Divisible by 5: {}", test);
}
// End at zero.
if test == 0 {
break;
}
println!("Loop current: {}", test);
test -= 1
}
}Divisible by 5: 10
Loop current: 10
Loop current: 9
Loop current: 8
Loop current: 7
Loop current: 6
Divisible by 5: 5
Loop current: 5
Loop current: 4
Loop current: 3
Loop current: 2
Loop current: 1
Divisible by 5: 0
While true. Rust supports a while-true loop, but this form of the while-loop is not the clearest way to express the loop. Instead we use the "loop" keyword.
fn main() {
while true {
}
}warning: denote infinite loops with `loop { ... }`
--> src/main.rs:2:5
...
Summary. With the while-loop, we can evaluate a simple or complex expression on each iteration of the loop. If the condition is true, the loop body is entered.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.