实现说明
函数 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:?}");
}