4.5 `break` 与 `continue`

break 与 continue — Comprehensive Rust

译文 · 基于 Comprehensive Rust

原文链接: https://google.github.io/comprehensive-rust/control-flow-basics/break-continue.html

4.5 break 与 continue

若要立即开始下一次迭代,使用 continue。

若要提前退出任意类型的循环,使用 break。 对 loop 而言,break 可以带一个可选表达式,该表达式会成为 loop 表达式的值。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// Copyright 2023 Google LLC
// SPDX-License-Identifier: Apache-2.0
fn main() {
    let mut i = 0;
    loop {
        i += 1;
        if i > 5 {
            break;
        }
        if i % 2 == 0 {
            continue;
        }
        dbg!(i);
    }
}

注意:loop 是唯一能返回非平凡值的循环结构。这是因为它保证只在 break 语句处返回(与 while 和 for 循环不同,后两者还可能在条件失败时返回)。


4.5.1 标签

01-标签 — Comprehensive Rust

最后修改 August 11, 2026: 更新 (70a5af133)