知识卡片
孤儿规则约束外部实现
Rust 对 trait 实施一致性规则,以避免两个 crate 为同一个类型定义冲突的实现。基本例中,自己的 trait 可实现于标准库类型,标准库 trait 可实现于自己的类型;把两个外部定义直接配对,如在应用中为 Vec 实现 Display,则不允许。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 泛型类型、trait 与生命周期 Traits: Defining Shared Behavior · 查看原书依据
But we can’t implement external traits on external types. For example, we can’t implement the Display trait on Vec<T> within our aggregator crate because Display and Vec<T> are both defined in the standard library and aren’t local to our aggregator crate. This restriction is part of a property called coherence, and more specifically the orphan rule, so named because the parent type is not present.
参考来源
- 位置:《The Rust Programming Language(第2版)》第10章 泛型类型、trait 与生命周期(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c10.xhtml`,块 0129)
- 结论依据:原文给出 Display 和 Vec 都是外部定义的反例,并解释避免多个实现争用的目的。
- 原始内容:But we can’t implement external traits on external types. For example, we can’t implement the Display trait on Vec<T> within our aggregator crate because Display and Vec<T> are both defined in the standard library and aren’t local to our aggregator crate. This restriction is part of a property called coherence, and more specifically the orphan rule, so named because the parent type is not present.