知识卡片
新类型满足孤儿规则
为外部类型实现外部 trait 容易让多个依赖各给出冲突实现。常见情况下,trait 或目标类型至少要有一个由当前 crate 定义,泛型实现还涉及覆盖约束。需要为外部类型提供额外 trait 行为时,可以给它套本地 newtype,再针对包装类型实现。这个实现只作用于包装对象。
相关卡片 [[新类型隔离业务语义]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Declarative macros newtype 与宏分担样板 · 查看原书依据
Before ending this section, I should mention that there is a Rust-specific reason for using newtypes: orphan rules. If you want to implement a given trait in Rust, either the trait, the type (e.g.
参考来源
- 位置:《Write Powerful Rust Macros》第02章《Declarative macros》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-2.xhtml#p104)
- 结论依据:原文以 Clone 与 String 的冲突说明一致性问题,再用本地包装获得实现位置。
- 原始内容:Before ending this section, I should mention that there is a Rust-specific reason for using newtypes: orphan rules. If you want to implement a given trait in Rust, either the trait, the type (e.g.