知识卡片
错误转换帮助简洁传播
为自定义错误实现From<子错误>,可让?把底层失败自动包装成正确变体,兼顾简洁与类型信息。应由定义公共错误的库提供必要转换,避免下游受外部类型实现规则限制。自动转换仍需有明确含义,不应把不同失败一律压成缺少上下文的同一种文字。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Chapter 1. Types Nested Errors · 查看原书依据
impl From<std::io::Error> for MyError { fn from(e: std::io::Error) -> Self { Self::Io(e) } } impl From<std::string::FromUtf8Error> for MyError { fn from(e: std::string::FromUtf8Error) -> Self { Self::Utf8(e) } } This prevents library users from suffering under the orphan rules themselves: they aren’t allowed to implement From on MyError, because both the tra
参考来源
- 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第1章《Nested Errors》(spine5;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch01.html;u027-ch01-032)。
- 结论依据:原文在“impl From<std::io::Error>”附近的定义、例子或代码支撑本卡核心说明:为自定义错误实现From<子错误>,可让?把底层失败自动包装成正确变体,兼顾简洁与类型信息。边界按已读前提解释;示例未执行。
- 原始内容:impl From<std::io::Error> for MyError { fn from(e: std::io::Error) -> Self { Self::Io(e) } } impl From<std::string::FromUtf8Error> for MyError { fn from(e: std::string::FromUtf8Error) -> Self { Self::Utf8(e) } } This prevents library users from suffering under the orphan rules themselves: they aren’t allowed to implement From on MyError, because both the tra