Home
Rust
while, loop Keywords
This page was last reviewed on Jul 8, 2024.
Dot Net Perls
While, loop. In Rust, we often use imperative looping statements like while and for. In addition, the loop keyword can be used for an infinite loop.
for
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jul 8, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.