Rust cycle
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.
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");
}
Running result:
1
2
3
EXIT
The Rust language has not yet been written as do-while
usage of this tutorial, but do
is defined as a reserved word and may be used in future versions.
In C language 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;
}
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);
}
}
Running result:
Value is: 10
Value is: 20
Value is: 30
Value is: 40
Value is: 50
In this program 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.
That’s for sure, 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]);
}
}
Running result:
a[0] = 10
a[1] = 20
a[2] = 30
a[3] = 40
a[4] = 50
loop
cycle
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 while (true)
operation of exiting the loop is realized in the body of the loop.
The Rust language 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;
}
}
Running result:
'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);
}
Running result:
The index of 'O' is 3