知识卡片
别名不能替代本地新类型
type MyError=String只是已有类型的别名,不创造本地类型,因此不能靠它为String补实现外部Error。struct MyError(String)则建立本地类型,可按规则实现Error及所需格式化能力。新类型改变类型身份,别名只改变名称;两者不能互换。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Chapter 1. Types Minimal Errors · 查看原书依据
A type alias doesn’t help either, because it doesn’t create a new type and so doesn’t change the error message: pub type MyError = String; impl std::error::Error for MyError {} error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate --> src/main.rs:41:5 | 41 | impl std::error::Error for MyError {} | ^^
参考来源
- 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第1章《Minimal Errors》(spine5;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch01.html;u026-ch01-029)。
- 结论依据:原文在“A type alias doesn’t help”附近的定义、例子或代码支撑本卡核心说明:type MyError=String只是已有类型的别名,不创造本地类型,因此不能靠它为String补实现外部Error。边界按已读前提解释;示例未执行。
- 原始内容:A type alias doesn’t help either, because it doesn’t create a new type and so doesn’t change the error message: pub type MyError = String; impl std::error::Error for MyError {} error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate --> src/main.rs:41:5 | 41 | impl std::error::Error for MyError {} | ^^