breakcontinue

If you want to exit any kind of loop early, use break. For loop, this can take an optional expression that becomes the value of the loop expression.

如果需要立即启动 下一次迭代,请使用 continue

fn main() {
    let (mut a, mut b) = (100, 52);
    let result = loop {
        if a == b {
            break a;
        }
        if a < b {
            b -= a;
        } else {
            a -= b;
        }
    };
    println!("{result}");
}

continuebreak 都可以选择接受一个标签参数,用来 终止嵌套循环:

fn main() {
    'outer: for x in 1..5 {
        println!("x: {x}");
        let mut i = 0;
        while i < x {
            println!("x: {x}, i: {i}");
            i += 1;
            if i == 3 {
                break 'outer;
            }
        }
    }
}

在本示例中,我们会在内循环 3 次迭代后终止外循环。

This slide should take about 4 minutes.
  • 请注意,loop 是唯一返回有意义的值的循环结构。 这是因为它保证至少被输入一次(与 whilefor 循环不同)。