Sub topic 13
The Orphan Rule and Coherence
This chapter assumes you can define a trait, implement it for a type, and read basic generic code. The earlier chapters on trait basics and blanket implementations cover that.
Coherence: one impl per type and trait
Rust requires that for any pair of a trait and a type, at most one implementation exists in the whole program. This property is called coherence. Without it, a call like value.summarize() could be ambiguous, and adding a dependency could silently change which code runs.
The orphan rule
The orphan rule is how the compiler enforces coherence across crates. You may write impl Trait for Type only if at least one of these is defined in your own crate:
- the trait
- the type
An implementation where both come from elsewhere is an orphan. It is rejected with error E0117.
| Trait | Type | Allowed in your crate? |
|---|---|---|
| Your own | Your own | Yes |
| Your own | Foreign, such as `Vec<i32>` | Yes |
| Foreign, such as `Display` | Your own | Yes |
| Foreign, such as `Display` | Foreign, such as `Vec<String>` | No |
Why it matters: suppose crate A and crate B each implemented Display for Vec<String>. A program that used both crates would have two competing impls. The orphan rule prevents this by allowing only the owner of the trait or the type to write the impl.
Working around it with a newtype
To implement a foreign trait for a foreign type, wrap the type in a tuple struct that your crate owns. This is the newtype pattern.
use std::fmt;
struct Wrapper(Vec<String>);
impl fmt::Display for Wrapper {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{}]", self.0.join(", "))
}
}
fn main() {
let w = Wrapper(vec![String::from("a"), String::from("b")]);
println!("{w}");
}Wrapper is local, so the impl is allowed. The output is [a, b]. The cost is that Wrapper does not automatically get the methods of Vec<String>. You reach them through self.0, or you forward the ones you need.
Overlapping impls
Coherence also rejects two impls that could apply to the same type, even when they live in one crate. If you write impl<T: Display> Describe for T and also impl Describe for i32, the compiler reports E0119, because i32 implements Display. Stable Rust has no specialization to pick the more specific impl.
Common errors
- Writing
impl Display for Vec<T>. Both items are foreign. Use a newtype. - Adding a blanket impl to a trait you own and then finding that existing impls conflict. Check for overlap before you add one.
- Expecting a downstream crate to fill the gap. Only the crate that owns the trait or the type can implement it.
Exercise
You write impl std::fmt::Display for Option<u8> in your crate. Does it compile? Why, or how would you fix it?
Show answer
No. Display and Option<u8> both come from the standard library, so the impl is an orphan and fails with E0117. Fix it by defining a local type, such as struct MaybeByte(Option<u8>);, and implementing Display for that.
Exercise
Your crate defines trait Tag { fn tag(&self) -> String; }. May you write impl Tag for Vec<i32>? Why?
Show answer
Yes. The trait Tag is local to your crate, so the orphan rule is satisfied even though Vec<i32> is foreign.