How to Bypass Rust's Orphan Rule with a Generic Trait Parameter
The article explains Rust's Orphan Rule[1], which triggers error E0117 when you implement a foreign trait for a foreign type. For example, the ToJson trait from a serialization library cannot be implemented for uuid::Uuid. The rule exists to keep implementations from different crates[2] from conflicting, a property called coherence[3]. The author says the rule still leaves a fairly wide door open.
The article describes two common workarounds. A library can build in support for many types through feature flags such as with-uuid, but this cannot cover every type and can lock in versions and fixed behavior. Wrapping each type in a NewType[4] works, but a complex model then fills with .0 unwrapping.
The proposed fix is to give the trait a generic parameter with a default, such as ToJson<Ctx = ()>. A user defines an empty local struct, MyApp, and implements ToJson<MyApp> for uuid::Uuid and chrono::DateTime<chrono::Utc>. Because MyApp is defined in the current crate, the rule is satisfied, and the local type must be a newly defined type, not a type alias.
Read the original edvong.comDiscussion
Discussion
Commenters mostly see this technique as a useful but awkward workaround, and many would prefer it as a built-in language feature. One suggests dropping the Orphan Rule for applications, and another proposes passing the context to trait methods so it can be looked up at call time. One commenter asks whether the custom type must appear at every call site through turbofish.
Sources
-
Edmond Vong
How to Bypass Rust's Orphan Rule


