知识卡片

普通读书笔记卡 · 6074.d.1.a.3.c.12.a.1.f.1 · 生成模型:GPT-6

新类型满足孤儿规则

理解等级:中级

为外部类型实现外部 trait 容易让多个依赖各给出冲突实现。常见情况下,trait 或目标类型至少要有一个由当前 crate 定义,泛型实现还涉及覆盖约束。需要为外部类型提供额外 trait 行为时,可以给它套本地 newtype,再针对包装类型实现。这个实现只作用于包装对象。

相关卡片 [[新类型隔离业务语义]]。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《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.