rust中实现循环的几种方式

8/22/2021 rust
fn main() {
    let arr = [1, 2, 3, 4, 5];
    method1(arr);
    method2(arr);
    method3(arr);
}

// loop方式
fn method1(data: [i32; 5]) {
    let mut index = 0;
    loop {
        if index >= data.len() {
            break;
        }
        println!("value is {}", data[index]);
        index += 1;
    };
}

// while方式
fn method2(data: [i32; 5]) {
    let mut index = 0;

    while index < data.len() {
        println!("value is {}", data[index]);
        index = index + 1;
    }
}

// for方式
fn method3(data: [i32; 5]) {
    for val in data.iter() {
        println!("value is {}", val);
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
Last Updated: 2/16/2023, 10:05:20 AM