The orphan rule prevents you from implementing a trait for a type if both the trait and the type are defined outside your current crate. This rule ensures coherence by guaranteeing that only one implementation of a specific trait for a specific type exists across the entire program, preventing conflicting definitions between different crates. You can implement an external trait on a local type, or a local trait on an external type, but never an external trait on an external type.
// This compiles: Local trait (Summary) on external type (Vec<T>)
trait Summary {
fn summarize(&self) -> String;
}
impl Summary for Vec<String> {
fn summarize(&self) -> String {
"A list of strings".to_string()
}
}
// This fails: External trait (Display) on external type (Vec<T>)
// use std::fmt;
// impl fmt::Display for Vec<String> { ... } // Error!