Coherence and orphan rules
Quick answer
Coherence prevents conflicting trait implementations from making method selection ambiguous. The orphan rules restrict which external trait and type combinations a crate may implement.
Design a local boundary
For a simple nongeneric implementation, you can implement a local trait for an external type, or an external trait for your local type. You cannot directly implement a foreign trait for a foreign type. Generic implementations have additional coverage restrictions; two otherwise legal implementations must not overlap. A local newtype often solves the foreign-type case.
struct Label(String);impl std::fmt::Display for Label { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "[{}]", self.0) }}fn main() { println!("{}", Label("ready".into())); }Expected stdout (not executed):
[ready]The wrapper is a local type with its own formatting contract.
impl std::fmt::Display for Vec<i32> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.len()) }}fn main() {}Expected: compilation fails; exact diagnostic not verified.
Both Display and Vec are foreign to this crate.
Common mistake
A type alias does not create a new local type.
Try it yourself
Create a newtype around Vec<i32> and implement Display for its length.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Coherence and orphan rules — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
You want custom Display for an external Vec type. Which approach is allowed under the simple orphan rule?
Coherence and orphan rules — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust struct Label(String); impl std::fmt::Display for Label { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "[{}]", self.0) } } fn main() { println!("{}", Label("ready".into())); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Coherence and orphan rules — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust impl std::fmt::Display for Vec<i32> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.len()) } } fn main() {} ``` Which outcome or interpretation best matches this example?