In Rust, we often use imperative looping statements like while and for. In addition, the loop keyword can be used for an infinite loop.
With while, we specify an exit condition in the first statement of the loop. And with the "loop" keyword, no exit condition is specified.
Rust supports the while
-keyword, and this is the classic while loop. It continues iterating while the specified condition is true.
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
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.
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
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 ...
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.