Skip to content
HN On Hacker News ↗

How to Bypass Rust's Orphan Rule

▲ 44 points • 6 comments • by todsacerdoti • 5d ago • HN discussion ↗

Pangram verdict · v3.3

We believe this text is mainly AI, with some human-written content.

96 %

AI likelihood · overall

AI
4% human-written 96% AI-generated
SEGMENTS · HUMAN 1 of 8
SEGMENTS · AI 7 of 8
WORD COUNT 1,473
PEAK AI % 100% · §1
Analyzed
Nov 21
backend: pangram/v3.3
Segments scanned
8 windows
avg 184 words each
Distribution
4 / 96%
human / AI fraction
Verdict
AI
Pangram v3.3

Article text · 1,473 words · 8 segments analyzed

Human AI-generated
§1 AI · 100%

Write Rust for long enough, and you are bound to run into error[E0117].Take a simple, everyday scenario. You pull in a serialization library that defines a ToJson trait, along with a third-party type library like uuid. You want to turn a uuid::Uuid into JSON, so you naturally write:impl ToJson for uuid::Uuid { fn to_json(&self) -> String { format!("\"{}\"", self) } }And the compiler immediately stops you:error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crateThis is Rust's well-known Orphan Rule. Once people hit this wall, they usually either complain that the compiler is too rigid or dutifully wrap the type in a NewType. But if you look closely at how the Orphan Rule actually works, it is not a dead end. By design, it leaves a pretty wide door open.What Is the Orphan Rule Actually Protecting Against?Setting the jargon aside, the logic behind the Orphan Rule is simple: if you want a type to implement a trait, at least one of those two things (the type or the trait) must belong to your own crate. In plain English, you don't get to make rules for someone else's types.Suppose crate A implements ToJson for uuid::Uuid and outputs a hyphenated UUID string, while crate B also implements ToJson for uuid::Uuid and outputs 32 raw hex characters without hyphens. If a project depends on both A and B, the compiler has a problem when it sees uuid.to_json(): which implementation should it pick?To prevent this kind of global conflict, Rust enforces coherence, and the Orphan Rule is how it gets enforced. There is nothing wrong with the rule itself. It keeps the Rust ecosystem from turning into a mess as dependency trees grow. The catch is that real-world projects constantly run into a very common need: making a third-party type implement a trait from another third-party crate. Neither the type nor the trait is yours, yet gluing libraries together like this happens all the time. So what can you do?Why the Two Usual Workarounds Fall ShortRight now, the Rust ecosystem mostly relies on two workarounds. Both appear to solve the problem on the surface, but because neither addresses the root cause, they get awkward fast.1. Building it into the libraryMany foundational crates take this route: since users can't write the impl themselves, the crate provides it internally. Because ToJson is defined inside the crate, implementing it for any external type satisfies the Orphan Rule. Open up the Cargo.toml of one of these crates, and you will see a long list of feature flags: with-uuid, with-chrono, with-time, with-jiff, with-url, with-rust-decimal, and so on.It looks helpful at first, but it tries to enumerate an open, constantly changing ecosystem inside a single crate. That approach has clear limits, and the downsides show up quickly:You can never support everything. Today the community favors chrono, tomorrow people switch to jiff, and next week your team builds its own internal Money type. If the library doesn't have built-in support, you are stuck waiting for a release or opening a PR yourself.Version lock-in. When a third-party type crate bumps its major version, your whole dependency tree gets stuck until the trait crate publishes a matching update.Hardcoded behavior. Maybe the library serializes DateTime<Utc> as an ISO-8601 string by default, while your API spec requires an integer timestamp in milliseconds. Because the implementation lives inside the library, you have no way to change it.2. Wrap it in a NewType yourselfWhen the library doesn't have built-in support, or its default behavior doesn't fit your needs, you fall back to the familiar NewType pattern:pub struct MyUuid(pub uuid::Uuid); impl ToJson for MyUuid { fn to_json(&self) -> String { format!("\"{}\"", self.0) } }Wrapping one or two types is fine. The trouble starts when a moderately complex domain model mixes Uuid, Url, DateTime, HashMap, and custom domain types all at once. Once you wrap everything into MyUuid, MyUrl, and MyDateTime, your business logic gets littered with .0, and you spend your time constantly wrapping and unwrapping values. It gets old very quickly.NewType is a genuinely useful pattern in Rust for expressing domain meaning, hiding internals, or enforcing invariants. The problem is that when you only use it to appease the Orphan Rule on types that didn't need a wrapper in the first place, your code bloats quickly.So is there a way to let users decide how third-party types implement a trait, without wrapping everything in NewTypes?Adding a Generic Slot to the TraitLet's go back to the rule: either the type or the trait must belong to the current crate.Many developers assume the compiler only looks at Trait and Type in impl Trait for Type. In fact, under Rust's Orphan Rule (RFC 2451), the trait's own generic type parameters are also part of the check.Put simply, in impl Trait<P> for Type, as long as a local type appears in the trait's generic parameters, and there are no uncovered type parameters before it, the compiler knows this implementation belongs exclusively to the current crate. No other crate can conflict with it, so the compiler lets it through.Take this example:impl ToJson<MyCtx> for uuid::Uuid { // ...

§2 AI · 100%

}ToJson is a foreign trait, and Uuid is a foreign type, but MyCtx is defined in the current crate.

§3 AI · 100%

Because it sits in the trait's generic parameter position, this impl satisfies the Orphan Rule.Following this idea, a library author only needs to take one extra step when designing a trait: leave a generic parameter on the trait as an extension point for users.For example:pub trait ToJson<Ctx = ()> { fn to_json(&self) -> String; }Notice that Ctx = () has a default type.

§4 Human · 0%

When the library implements ToJson for basic types like i32 and String, it makes those implementations generic over any Ctx:impl<Ctx> ToJson<Ctx> for i32 { fn to_json(&self) -> String { self.to_string() } } impl<Ctx> ToJson<Ctx> for String { fn to_json(&self) -> String { format!("\"{}\"", self) } }This way, regular users never even notice Ctx exists.

§5 AI · 100%

Everything works the exact same way as before, with () as the default context.When you do need to plug in third-party types, you just define an empty marker struct in your own crate:pub struct MyCtx;Then you can write implementations for any third-party type you want:impl ToJson<MyCtx> for uuid::Uuid { fn to_json(&self) -> String { format!("\"{}\"", self) } } impl ToJson<MyCtx> for chrono::DateTime<chrono::Utc> { fn to_json(&self) -> String { self.timestamp_millis().to_string() } }The compiler looks at this and sees: ToJson is foreign, Uuid and DateTime are foreign, but MyCtx is local to your crate. No other crate can write a conflicting implementation using your MyCtx, so global coherence is completely safe. It compiles right away.You can think of this conversion setup as a web of relationships, with your local MyCtx type as its root. A handy way to picture it is a bunch of grapes, where MyCtx is the stem. Once you grab that stem, it doesn't matter how many third-party types hang off it (Uuid, Url, DateTime, HashMap, and so on). You lift the whole bunch at once, and the compiler accepts all of them as local implementations.Better yet, you can define more than one stem in the same project. For instance, your HTTP API layer can use ApiCtx to format timestamps as strings, while an internal RPC layer uses RpcCtx to format them as integer timestamps. Both sets of rules live under separate contexts, completely isolated at compile time, with zero conflict.One detail to watch out for: the local type has to be a real, newly defined type. Creating a type alias for a foreign type will not work.The Position of the Local Type MattersAt this point, you might think that dropping a local type MyCtx anywhere into a trait's generic list solves the Orphan Rule for good.

§6 AI · 100%

Most of the time, it does.

§7 AI · 100%

But if your trait has more than one generic parameter, or if you want to write a generic impl, there is an ordering restriction that is easy to trip over.When the compiler runs its Orphan Rule check, it scans the types in a fixed order: first the Self type, then the trait's 1st generic parameter, then the 2nd, and so on. The rule comes down to one sentence: no bare generic type parameter T may appear before the first local type.Code makes this clearest. Suppose an external crate defines ForeignTrait<A, B> and ForeignType, and you define MyCtx locally:// ✅ Allowed: scans ForeignType, then hits local MyCtx first; the trailing T is unrestricted impl<T> ForeignTrait<MyCtx, T> for ForeignType {} // ❌ Error: hits a bare T before seeing MyCtx impl<T> ForeignTrait<T, MyCtx> for ForeignType {} // ❌ Error: hits a bare T right away in Self, before MyCtx gets a chance impl<T> ForeignTrait<MyCtx, String> for T {}The only word to pay attention to here is "bare".

§8 AI · 100%

In Rust terminology, this is called an uncovered type parameter. A plain T is uncovered.