In addition to the flexible conditional statements in Rust, the design of loop structure is also very mature. As an experienced developer, you should be able to feel this. Running result: The Rust language has not yet been written as In C language Running result: In this program That’s for sure, Running result: Experienced developers must have encountered several situations where a loopcannot determine whether to continue at the beginning and end of the loop and must control the loop somewhere in the middle of the loop. If we encounter this kind of situation, we will often be in a The Rust language has a native infinite loop structure - Running result: Running result: 7.10.1.
while
cycle #
while
loop is the most typical conditional statement loop:Example #
fn main() {
let mut number = 1;
while number != 4 {
println!("{}", number);
number += 1;
}
println!("EXIT");
}
1
2
3
EXIT
do-while
usage of this tutorial, but
do
is defined as a reserved word and may be used in future versions.
for
loops use ternary statements to control loops, but this is not used in Rust, so you need to use
while
cycle instead of:C language #
int i;
for (i = 0; i < 10; i++) {
// loop body
}
Rust #
let mut i = 0;
while i < 10 {
// loop body
i += 1;
}
7.10.2.
for
cycle #
for
loops are the most commonly used loop structures, often used to traverse a linear data structure (such as an array).
for
loop through the array:Example #
fn main() {
let a = [10, 20, 30, 40, 50];
for i in a.iter() {
println!("Value is : {}", i);
}
}
Value is: 10
Value is: 20
Value is: 30
Value is: 40
Value is: 50
for
loop completes traversing the array a. The
a.iter()
iterator, which stands for a iterator, will not be repeated until you learn about the chapter on objects.
for
loop can actually access the array through thesubscript:Example #
fn main() {
let a = [10, 20, 30, 40, 50];
for i in 0..5 {
println!("a[{}] = {}", i, a[i]);
}
}
a[0] = 10
a[1] = 20
a[2] = 30
a[3] = 40
a[4] = 50
7.10.3.
loop
cycle #
while
(true)
operation of exiting the loop is realized in the body of the loop.
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;
}
}
'R'
'U'
'N'
loop
loop can be passed through
break
keyword is similar to
return
exits the entire loop as well and gives a return value to the outside. This is a very ingenious design because
loop
such a loop is often used as a lookup tool, and of course hand in the result if you find something: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!(" \\'O\\' the index of is {}", location);
}
The index of 'O' is 3