Rust Loops
Rust, in addition to its flexible conditional statements, also has a mature design for loop structures. Experienced developers should be able to appreciate this.
while Loop
The while loop is the most typical conditional loop:
Example
fn main() {
let mut number = 1;
while number != 4 {
println!("{}", number);
number += 1;
}
println!("EXIT");
}
Execution result:
1
2
3
EXIT
As of the time of writing this tutorial, Rust does not have a do-while loop, but "do" is reserved as a keyword, which might be used in future versions.
In C, the for loop uses a ternary statement to control the loop, but Rust does not have this usage; instead, you need to use a while loop:
C Language
int i;
for (i = 0; i < 10; i++) {
// Loop body
}
Rust
let mut i = 0;
while i < 10 {
// Loop body
i += 1;
}
for Loop
The for loop is the most commonly used loop structure and is often used to iterate over a linear data structure (like an array). Example of iterating over an array with a for loop:
Example
fn main() {
let a = [10, 20, 30, 40, 50];
for i in a.iter() {
println!("Value is : {}", i);
}
}
Execution result:
Value is : 10
Value is : 20
Value is : 30
Value is : 40
Value is : 50
This program iterates over the array a
using a.iter()
, which represents the iterator of a
. This will be explained further in the sections about objects.
Of course, the for loop can also access array elements by index:
Example
fn main() {
let a = [10, 20, 30, 40, 50];
for i in 0..5 {
println!("a[{}] = {}", i, a[i]);
}
}
Execution result:
a[0] = 10
a[1] = 20
a[2] = 30
a[3] = 40
a[4] = 50
loop Loop
Experienced developers have certainly encountered situations where a loop cannot be determined to continue at the beginning or end, but must be controlled in the middle of the loop body. In such cases, we often implement an exit in the middle of a while (true)
loop.
Rust has a native infinite loop structure — loop
:
Example
fn main() {
let s = ['R', 'U', 'N', 'O', 'O', 'B'];
let mut i = 0;
loop {
let ch = s[i];
if ch == 'O' {
break;
}
println!("\'{}\'", ch);
i += 1;
}
}
Execution result:
'R'
'U'
'N'
The loop
can be exited with the break
keyword, similar to return
, and can return a value to the outside. This is a clever design, as loop
is often used as a search tool, and if something is found, the result needs to be returned:
Example
fn main() {
let s = ['R', 'U', 'N', 'O', 'O', 'B'];
let mut i = 0;
let location = loop {
let ch = s[i];
if ch == 'O' {
break i;
}
i += 1;
};
println!("Index of 'O' is {}", location);
}
Execution result:
Index of 'O' is 3