Search CTRL + K

Orphan Rules

孤儿规则 指使用第三方库(包括标准库)开发时,可以:


这是为了确保别人的代码(对某个 type 实现 trait)不会破坏你的代码(对某个 type 实现 trait),如果没有这条规则,库和使用者都对某个第三方 type 实现了第三方的 trait,编译器将无法抉择使用哪一个。

[!CITE] The Rust Programming Language
But we can’t implement external traits on external types. For example, we can’t implement the Display trait on Vec within our aggregator crate, because Display and Vec 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. This rule ensures that other people’s code can’t break your code and vice versa. Without the rule, two crates could implement the same trait for the same type, and Rust wouldn’t know which implementation to use.[1]
  1. ↩︎