English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Rust, in addition to flexible conditional statements, also has a mature design of loop structures. This should be felt by experienced developers.
The while loop is the most typical conditional statement loop:
fn main() { let mut number = 1; while number != 4 println!("{}", number); number += 1; } println!("EXIT"); }
Running Result:
1 2 3 EXIT
Rust language has not had do up to the date of this tutorial.-The usage of while, but do is specified as a reserved word, which may be used in future versions.
In C Language, the for loop uses ternary statements to control the loop, but in Rust there is no such usage, and it needs to be replaced with a while loop:
int i; for (i = 0; i < 10; i++) { // Loop body }
let mut i = 0; while i < 10 // Loop body i += 1; }
The for loop is the most commonly used loop structure, often used to traverse a linear data structure (such as an array). The for loop traverses an array:
fn main() { 10 2 3 4 5 for i in a.iter() { println!("The value is : {}", i); } }
Running Result:
The value is : 10 The value is : 20 The value is : 30 The value is : 40 The value is : 50
fn main() { 10 2 3 4 5 5 println!("a[{}] = {} } }
Running Result:
a[0] = 10 a[1] = 20 a[2] = 30 a[3] = 40 a[4] = 50
Experienced developers have certainly encountered several situations where a loop cannot determine whether to continue the loop at the beginning and end, and must control the loop at some point in the loop body. If faced with such a situation, we often implement the operation of exiting the loop in the middle of a while (true) loop body.
Rust has a native infinite loop structure called loop:
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'
The loop loop can exit the entire loop and return a value to the outside by using the break keyword, similar to return. This is a very clever design, because loops like loop are often used as search tools, and of course, the result should be handed over if something is found:
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!("The index of 'O' is {}", location); }
Running Result:
The index of 'O' is 3