知识卡片
动态错误保留对象而擦除类型
Box能在不枚举所有子错误的情况下保存不同错误对象。调用者先通过Error接口取得格式化与来源链,不能直接把它当成已知具体类型;满足条件时仍可检查或向下转换。它保留对象,与仅保留一段格式化文字不同,但公共接口的分类能力更弱。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Chapter 1. Types Trait Objects · 查看原书依据
Box<dyn Error>), General(String), } impl std::fmt::Display for WrappedError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Wrapped(e) => write!(f, "Inner error: {}", e), Self::General(s) => write!(f, "{}", s), } } } It turns out that this is possible, but it’s surprisingly subtle. Part of the difficulty comes from t
参考来源
- 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第1章《Trait Objects》(spine5;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch01.html;u028-ch01-034)。
- 结论依据:原文在“Box<dyn Error>”附近的定义、例子或代码支撑本卡核心说明:Box<dyn Error>能在不枚举所有子错误的情况下保存不同错误对象。边界按已读前提解释;示例未执行。
- 原始内容:Box<dyn Error>), General(String), } impl std::fmt::Display for WrappedError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Wrapped(e) => write!(f, "Inner error: {}", e), Self::General(s) => write!(f, "{}", s), } } } It turns out that this is possible, but it’s surprisingly subtle. Part of the difficulty comes from t