← 中文资源

简体中文版本

用 break 让 loop 返回值

loop 是表达式,break 带出的值就是整个循环的值:重试成功即返回、预算耗尽兜底退出,所有 break 的类型必须一致,无值 loop 返回 ()。

阅读英文原文

实现说明

底层就是函数 try_load、main。 没有任何东西会抛出:失败路径就是调用方必须 match 的 Result 变体。输入的每种形态各占一个 match 分支,编译器检查这套分支是否完整。

使用要点

  • 错误处理是类型化的——每个 Result 都要 match 或用 ? 转发。
  • 跑完文件,输出里会留下标记——attempt、giving up after、loaded:。
  • main 按顺序串起 try_load;运行文件就会把这个流程跑一遍。

常见问题

错误处理是什么风格?

每个可能失败的操作都返回 Result,不会被悄悄丢弃。

运行「用 break 让 loop 返回值」会打印什么?

整个文件跑完,输出行以 attempt、giving up after、loaded: 这类前缀开头。

签名一览:fn try_load(attempt: u32) -> Result<&'static str, String>

核心语句

Err(err) if attempt < 3 => {
    println!("attempt {attempt} failed: {err}; retrying");
    sleep(Duration::from_millis(10));
}
Err(err) => {
    println!("giving up after {attempt} attempts: {err}");
    break "defaults";
}
fn try_load(attempt: u32) -> Result<&'static str, String> {
    match attempt {
        1 => Err("cache cold".to_string()),
        2 => Err("replica lagging".to_string()),
        _ => Ok("config v7"),
    }
}

代码示例

use std::thread::sleep;
use std::time::Duration;

// simulates a loader that fails the first two attempts and succeeds on the third
fn try_load(attempt: u32) -> Result<&'static str, String> {
    match attempt {
        1 => Err("cache cold".to_string()),
        2 => Err("replica lagging".to_string()),
        _ => Ok("config v7"),
    }
}

fn main() {
    let mut attempt = 0;

    // loop is an expression: the value carried by break is the value of the whole loop
    let config = loop {
        attempt += 1;
        match try_load(attempt) {
            // success: break the value out
            Ok(config) => break config,
            Err(err) if attempt < 3 => {
                println!("attempt {attempt} failed: {err}; retrying");
                sleep(Duration::from_millis(10));
            }
            // budget exhausted: break with a fallback to avoid looping forever
            Err(err) => {
                println!("giving up after {attempt} attempts: {err}");
                break "defaults";
            }
        }
    };
    println!("loaded: {config}");

    // a loop that yields a value requires every break to agree on that type; a value-less loop has type ()
    let countdown = loop {
        attempt += 1;
        if attempt >= 5 {
            break attempt; // a different loop from the one above, with unrelated types
        }
    };
    println!("countdown reached: {countdown}");
}