Rust Loops
A loop statement allows the execution of a statement or group of statements multiple times. There are three types of loop statement in Rust.
- ‘for’ loop – Useful when it is known in advance the number of times the statements within the loop need to be executed.
- ‘while’ loop – Repeats a statement or group of statements while an expression evaluates to true. There is a condition to get into the loop, so if the condition evaluates to true at the beginning, then the statements inside the loop will never execute.
- ‘loop’ – This type of loop will execute the statements within indefinitely, so requires a statement to explicitly break out of the loop.
‘for’ Loop
A 'for' loop in Rust can work on a range, or a collection of values, such as an array and takes the following form.
for value in range/collection { // Statement(s) to execute. }
The following example specifies a range of one to five, and displays the value of 'i', which is the current value of the range, each time through the loop.
for i in 1..=5 { println!("{}", i); }
The resulting output is shown below.
1 2 3 4 5
A 'for' loop can also work on a collection of values, such as an array is a special type of variable, that contains multiple values of the same type.
Here, the 'for' loop is used to print out the names contained in the array.
let fnames = &[ "Bob", "George", "Fred", "Alan" ]; for i in fnames { println!("{}", i); }
This displays the array of names as follows.
Bob George Fred Alan
‘while’ Loop
As mentioned above, the ‘while’ loop has a condition, which must evaluate to true before the statements within it can be executed. The condition within the loop can be enclosed in parenthesis, however, by convention, these are omitted, unless they are absolutely necessary.
while condition { // Statement(s) to execute. }
In the below example, a variable is declared and initialised to one, then the ‘while’ loop checks to see that the variable is less than or equal to five before outputting it to the screen and incrementing the variable by one.
let mut i = 1; while i <= 5 { println!("{}", i); i += 1; }
The output will be the same as in the ‘for’ loop example above. Note that if the variable ‘i’ had been declared and initialised to six or above, then the statements within the loop would not be executed at all.
'loop'
A 'loop' is the simplest of the three loops to declare, with no condition to enter or exit the loop.
loop { // Statement(s) to execute. }
A statement, such as a 'break' statement can be used to stop execution of the loop. Here, a variable is declared and initialised to one, then the loop displays it and increments by one. An 'if' statement is used to check if the value of the variable is greater than five and when it meets this condition a 'break' statement stops the loop executing.
let mut i = 1; loop { println!("{}", i); i += 1; if i > 5 { break; } }
The resulting output is the same as the 'for' and 'while' loop examples above.