知识卡片
让任务函数传播错误
动作型接口可返回 Result<(), Box<dyn Error>>。Ok(()) 表示动作完成,? 会提前返回可转换为目标错误类型的 Err。调用者若只需关注错误,可写 if let Err(e) = run(config)。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- I/O 项目:构建命令行程序 Extracting Logic from main · 查看原书依据
For the error type, we used the trait object Box<dyn Error> (and we’ve brought std::error::Error into scope with a use statement at the top ❶). We’ll cover trait objects in Chapter 17. For now, just know that Box<dyn Error> means the function will return a type that implements the Error trait, but we don’t have to specify what particular type the return value will be.
参考来源
- 位置:《The Rust Programming Language(第2版)》第12章 I/O 项目:构建命令行程序(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c12.xhtml`,块 0145)
- 结论依据:原文解释 `Box<dyn Error>` 让不同底层错误类型进入同一返回类型。
- 原始内容:For the error type, we used the trait object Box<dyn Error> (and we’ve brought std::error::Error into scope with a use statement at the top ❶). We’ll cover trait objects in Chapter 17. For now, just know that Box<dyn Error> means the function will return a type that implements the Error trait, but we don’t have to specify what particular type the return value will be.