Rust 循环

loop / while / for、循环标签、以及 `loop` 的返回值。

Beginner
Key Points`loop` 是无限循环,可以用 `break 值` 把结果带出来。

三种循环

Rust
fn main() {
    // for:遍历迭代器(最常用)
    for i in 1..=3 {
        print!("{} ", i);
    }
    println!();

    // while:条件为真时循环
    let mut n = 3;
    while n > 0 {
        print!("{} ", n);
        n -= 1;
    }
    println!();

    // loop:无限循环,靠 break 退出
    let mut count = 0;
    loop {
        count += 1;
        if count == 3 {
            break;
        }
    }
    println!("{}", count);
}
Output
1 2 3 
3 2 1 
3

loop 带返回值

Rust
fn main() {
    let mut n = 1;
    let result = loop {
        n *= 2;
        if n > 100 {
            break n;        // 把值带出来
        }
    };
    println!("{}", result);
}
Output
128

loop is the only loop that yields a value: break n becomes the value of the whole expression. That removes the need for a pre-declared mut holder.

区间

Rust
fn main() {
    for i in 0..3 { print!("{} ", i); }        // 0 1 2
    println!();
    for i in 0..=3 { print!("{} ", i); }       // 0 1 2 3
    println!();
    for i in (0..10).step_by(3) { print!("{} ", i); }  // 0 3 6 9
    println!();
    for i in (1..=5).rev() { print!("{} ", i); }       // 5 4 3 2 1
    println!();
}
Output
0 1 2 
0 1 2 3 
0 3 6 9 
5 4 3 2 1 
FormMeaning
a..b左闭右开
a..=b左闭右闭
..b / a..省略一端
..整个范围(用于切片)

标签

Rust
fn main() {
    'outer: for i in 0..3 {
        for j in 0..3 {
            if i * j == 2 {
                println!("找到 {} {}", i, j);
                break 'outer;
            }
        }
    }

    // continue 也可以带标签
    'a: for i in 0..3 {
        for j in 0..3 {
            if j == 1 {
                continue 'a;
            }
            print!("({},{}) ", i, j);
        }
    }
    println!();
}
Output
找到 1 2
(0,0) (1,0) (2,0) 

Labels start with a quote and sit before the loop. break 'outer exits the outer loop directly — the idiomatic way out of nesting, cleaner than a flag variable.

遍历容器

Rust
fn main() {
    let v = vec![10, 20, 30];

    // 按值遍历(消费 v)
    for x in v {
        print!("{} ", x);
    }
    println!();

    let v2 = vec![1, 2, 3];

    // 按引用遍历(不消费)
    for x in &v2 {
        print!("{} ", x);
    }
    println!();

    // 按可变引用(可改)
    let mut v3 = vec![1, 2, 3];
    for x in &mut v3 {
        *x *= 2;
    }
    println!("{:?}", v3);
}
Output
10 20 30 
1 2 3 
[2, 4, 6]
for x in v **moves v** (unusable afterwards). Use for x in &v to keep it. This is the most common source of "value moved here" errors.

Friends & Partners