Sub topic 13
The orphan rule and coherence
This chapter assumes you can write a trait, implement it for a struct, and read a generic impl<T: Bound> block. You should also know that a crate is one compilation unit, and that your program depends on other crates such as std.
Why Rust restricts implementations
Coherence is the guarantee that, for any trait and any type, at most one implementation applies. Without it, a call like value.describe() could mean different things depending on which crates were linked in. Rust enforces coherence with two checks:
- The orphan rule limits where an implementation may be written.
- The overlap check rejects two implementations that could apply to the same type.
Both checks run when a crate is compiled. They are the reason you can add a dependency without silently changing how existing code behaves.
The orphan rule
You may write impl Trait for Type only if the trait or the type is defined in your crate. An implementation where both come from other crates is an orphan, and the compiler rejects it.
| Trait | Type | Allowed in your crate? |
|---|---|---|
| Local | Local | Yes |
| Local | Foreign (`Vec<i32>`, `bool`) | Yes |
| Foreign (`Display`) | Local | Yes |
| Foreign (`Display`) | Foreign (`Vec<i32>`) | No |
The following program uses the two allowed mixed cases.
use std::fmt;
trait Describe {
fn describe(&self) -> String;
}
// Local trait, foreign types.
impl Describe for Vec<i32> {
fn describe(&self) -> String {
format!("{} numbers", self.len())
}
}
impl Describe for bool {
fn describe(&self) -> String {
if *self { String::from("yes") } else { String::from("no") }
}
}
struct Meters(f64);
// Foreign trait, local type.
impl fmt::Display for Meters {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} m", self.0)
}
}
fn main() {
println!("{}", vec![1, 2, 3].describe());
println!("{}", true.describe());
println!("{}", Meters(4.5));
}Now try the forbidden case: impl fmt::Display for Vec<i32>. Both Display and Vec belong to std, so the compiler refuses:
error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crateIf this were allowed, two unrelated crates could each implement Display for Vec<i32>. A program that used both would have no way to choose between them.
Generic traits and the "first local type" rule
The real rule is a little wider than "trait or type is local". A trait may have type parameters, so From<Celsius> for f64 involves two types: f64 (the Self type) and Celsius. The orphan rule is satisfied when at least one of these types is local, and no uncovered type parameter appears before it.
struct Celsius(f64);
// Foreign trait From, foreign Self type f64, but the trait argument is local.
impl From<Celsius> for f64 {
fn from(c: Celsius) -> f64 {
c.0
}
}
fn main() {
let x: f64 = Celsius(21.5).into();
println!("{x}");
}An uncovered type parameter is a bare T that is not wrapped inside another type. impl<T> From<Celsius> for T is rejected with E0210, because T stands for any type, including ones that might later gain a conflicting implementation. impl<T> From<Celsius> for Vec<T> is accepted, because T is covered by Vec<...> and Celsius is local.
Working around the rule with a newtype
When you need a foreign trait on a foreign type, wrap the type in a local tuple struct. This is the newtype pattern, and the wrapper is a local type, so the implementation is legal.
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}");
}This prints [a, b]. The cost is that Wrapper does not expose the methods of Vec<String>. You either reach inside with self.0 or forward the methods you need. Implementing Deref is a common shortcut, but use it with care, because it makes the wrapper act like the inner type everywhere.
The overlap check
Even when every implementation passes the orphan rule, two of them cannot apply to the same type. Recall the blanket implementation from the previous chapter:
use std::fmt::Display;
trait Describe {
fn describe(&self) -> String;
}
impl<T: Display> Describe for T {
fn describe(&self) -> String {
format!("<{}>", self)
}
}
struct Opaque;
impl Describe for Opaque {
fn describe(&self) -> String {
String::from("opaque")
}
}
fn main() {
println!("{}", 7.describe());
println!("{}", Opaque.describe());
}This compiles. Opaque does not implement Display, and only this crate can add that implementation, so the two Describe implementations can never overlap. Replace Opaque with Vec<i32> and the compiler reports E0119 (conflicting implementations) with a note that "upstream crates may add a new impl of trait std::fmt::Display for type std::vec::Vec<i32> in future versions". Today Vec<i32> has no Display, but the standard library is allowed to add one. The compiler rejects the code now so that a future std update cannot break it.
Fundamental types and semver
A few standard types are marked #[fundamental]: &T, &mut T, Box<T>, and Pin<T>. The compiler treats them as transparent for the orphan rule, so impl Display for Box<Local> and impl Display for &Local are accepted when Local is your type. Most other wrappers, such as Vec<Local> or Option<Local>, are not transparent. impl Display for Vec<Local> is therefore rejected.
The rule also protects semantic versioning. Adding an implementation of a trait is normally a non-breaking change for the crate that owns the trait. A blanket implementation such as impl<T: Display> Describe for T is the exception: adding one to an existing trait can break downstream crates, because it may overlap with their implementations.
Common errors and how to respond
| Error | Meaning | Usual fix |
|---|---|---|
| E0117 | Foreign trait on a foreign type | Wrap the type in a newtype, or define your own trait |
| E0210 | Uncovered type parameter before the first local type | Implement for a concrete type, or cover the parameter |
| E0119 | Two implementations may apply to one type | Narrow the blanket bounds, or remove one implementation |
Exercise
You depend on a crate geometry that defines trait Area and struct Rect. You want impl Area for Rect in your own crate, and also impl Area for Vec<Rect>. Which of these is allowed, and what could you do about the other one?
Show answer
Neither is allowed. Both Area and Rect belong to geometry, so impl Area for Rect is an orphan implementation. impl Area for Vec<Rect> is also rejected, because Vec is foreign and Vec<Rect> is not a local type. Vec is not fundamental, so the local-looking Rect inside it does not count. Wrap the types in your own newtypes (for example struct MyRect(Rect)), or ask the geometry crate to provide the implementations.
Exercise
Explain why impl<T> From<Celsius> for T is rejected when Celsius is a local type, but impl From<Celsius> for f64 is accepted.
Show answer
The first form has a bare type parameter T as the Self type, and it appears before the first local type (Celsius). T could be any type, including types that other crates control, so a future implementation elsewhere could overlap with it. The compiler rejects it with E0210. The second form uses the concrete foreign type f64 with no uncovered parameters, and the local Celsius appears as a trait argument, so the orphan rule is satisfied.