Rust Loops
In addition to flexible conditional statements, Rust's loop structures are also very well-designed. As a battle-hardened developer, you should be able to sense this.
while Loop
The while loop is the most typical conditional loop:
Example
let mut number = 1;
while number != 4 {
println!("{}", number);
number += 1;
}
println!("EXIT");
}
Output:
1 2 3 EXIT
As of the writing of this tutorial, Rust does not have a do-while construct, but `do` is specified as a reserved word and may be used in future versions.
In C, the for loop uses a three-expression statement to control the loop, but Rust does not have this construct, so a while loop must be used instead:
C language
for (i = 0; i < 10; i++) {
// loop body
}
Rust
while i < 10 {
// loop body
i += 1;
}
for Loop
The for loop is the most commonly used loop construct, often used to iterate over a linear data structure (such as an array). A for loop iterates over an array:
Example
let a = [10, 20, 30, 40, 50];
for i in a.iter() {
println!("Value is: {}", i);
}
}
Output:
值为 : 10 值为 : 20 值为 : 30 值为 : 40 值为 : 50
The for loop in this program iterates over array a. `a.iter()` represents the iterator of a; we won't go into detail before learning about objects.
Of course, the for loop can also access the array by index:
Example
let a = [10, 20, 30, 40, 50];
for i in 0..5 {
println!("a[{}] = {}", i, a[i]);
}
}
Output:
a[0] = 10 a[1] = 20 a[2] = 30 a[3] = 40 a[4] = 50
loop Loop
Seasoned developers have certainly encountered situations where a loop cannot determine at the beginning or end whether to continue, and the loop execution must be controlled somewhere in the middle of the loop body. In such cases, we often implement an early exit from the loop inside a `while (true)` loop.
Rust has a native infinite loop construct — `loop`:
Example
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;
}
}
Output:
'R' 'U' 'N'
A `loop` loop can use the `break` keyword, similar to `return`, to exit the entire loop and provide a return value to the outside. This is a very clever design, because a `loop` loop is often used as a search tool; if something is found, of course the result should be handed out:
Example
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!(" \'O\''s index is {}", location);
}
Output:
'O' 的索引为 3Other Extensions