Looping
For repeating pieces of code, Rust has the common while
loop, again without parentheses around the condition:
// from Chapter 3/code/loops.rs fn main() { let max_power = 10; let mut power = 1; while power < max_power { print!("{} ", power); // prints without newline power += 1; // increment counter } }
This prints the following output:
1 2 3 4 5 6 7 8 9
To start an infinite loop, use the loop
statement, as shown below:
loop { power += 1; if power == 42 { // Skip the rest of this iteration continue; } print!("{} ", power); if power == 50 { print!("OK, that's enough for today"); break; // exit the loop } }
All the power
values including 50
but except 42
are printed; then the loop stops with the statement break
. The value 42
is not printed because of the continue
statement. So, loop
is equivalent to a while true
and a loop
with a conditioned...