← 中文资源

简体中文版本

迭代器 sum 对 Result 短路

迭代器的 sum 对 Result 条目同样生效:Ok 值逐个累加,遇到第一个 Err 就短路停止,报错带上下文,后面的行不会再解析。

阅读英文原文

实现说明

函数 parse_ms、main是行为的主要来源。 可能失败的操作返回 Result,调用方必须显式处理两个分支。

使用要点

  • 错误处理是类型化的——每个 Result 都要 match 或用 ? 转发。
  • 每一步打印都带着自己的标签:total:、stopped:。
  • 运行整个文件:main 会依次驱动 parse_ms。

常见问题

错误是如何上报的?

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

运行「迭代器 sum 对 Result 短路」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 total:、stopped: 标签标明各步骤。

主签名形如 fn parse_ms(raw: &str) -> Result<u64, String>

核心语句

let stopped: Result<u64, String> = dirty.iter().map(|row| parse_ms(row)).sum();
let total: Result<u64, String> = rows.iter().map(|row| parse_ms(row)).sum();
fn parse_ms(raw: &str) -> Result<u64, String> {
    raw.parse::<u64>().map_err(|e| format!("{raw}: {e}"))
}

代码示例

fn parse_ms(raw: &str) -> Result<u64, String> {
    raw.parse::<u64>().map_err(|e| format!("{raw}: {e}"))
}

fn main() {
    let rows = ["120", "40", "7"];

    // the Sum impl for Result: Ok values accumulate one by one, and the first Err short-circuits
    let total: Result<u64, String> = rows.iter().map(|row| parse_ms(row)).sum();
    println!("total: {total:?}");

    let dirty = ["120", "oops", "7"];

    // the error surfaces with the bad line's context and the remaining lines are never parsed
    let stopped: Result<u64, String> = dirty.iter().map(|row| parse_ms(row)).sum();
    println!("stopped: {stopped:?}");
}