Rust orphan rule: add a generic Ctx parameter to the trait to avoid NewType wrappers

The post starts with a common Rust stumble. You pull in a serialization library that defines a ToJson trait and a type library such as uuid, then try to implement ToJson for uuid::Uuid. The compiler stops you with error E0117: only traits defined in the current crate can be implemented for types defined outside of the crate. This is the Orphan Rule. The article's author says it is not a dead end, because by design it leaves a wide door open.

The rule exists for coherence. At least one of the two, the type or the trait, must belong to your own crate. The author's example: crate A implements ToJson for Uuid and prints a hyphenated string, crate B implements it too and prints 32 raw hex characters. If a project depends on both, the compiler cannot tell which implementation to pick for uuid.to_json(). The Orphan Rule prevents that global conflict. The author calls the rule itself sound; the pain is that real projects often need a third-party type to implement a trait from another third-party crate.

The post says the ecosystem mostly relies on two workarounds, and both get awkward. The first is building support into the trait's library. Such crates carry long lists of feature flags (with-uuid, with-chrono, with-time, with-jiff, with-url, with-rust-decimal and so on). The author names three downsides: a library can never support every type (if the community moves from chrono to jiff, or your team builds its own Money type, you wait for a release or send a PR); version lock-in, since when a third-party type crate bumps its major version the whole dependency tree is stuck until the trait crate publishes a matching update; and hardcoded behavior, for instance a library that serializes DateTime as an ISO-8601 string when your API spec wants an integer timestamp in milliseconds.

The second workaround is the NewType, such as a MyUuid struct wrapping uuid::Uuid. Wrapping one or two types is fine. In a domain model that mixes Uuid, Url, DateTime, HashMap and custom types, business logic ends up littered with .0 and constant wrapping and unwrapping. The author still calls NewType a genuinely useful pattern for domain meaning, hiding internals or enforcing invariants. The complaint is about using it only to appease the Orphan Rule on types that did not need a wrapper.

The proposed alternative rests on a detail many developers miss. Under the Orphan Rule (RFC 2451), the trait's own generic type parameters are part of the check too. In an impl of Trait

for Type, if a local type appears in the trait's generic parameters and no uncovered type parameter comes before it, the compiler knows the implementation belongs exclusively to the current crate, so no other crate can conflict with it.

So the library author declares the trait with a generic parameter that has a default type, written ToJson<Ctx = ()>, and implements its basic types (the post uses i32 and String) generically for any Ctx. Ordinary users never notice the parameter, and everything works as before with () as the default context. When a user needs third-party types, they define an empty marker struct in their own crate, MyCtx, and write impl ToJson for uuid::Uuid and impl ToJson for chrono::DateTimechrono::Utc. In the post's example the DateTime impl emits milliseconds since the epoch. ToJson, Uuid and DateTime are all foreign, but MyCtx is local, so the compiler accepts it. The author pictures MyCtx as the stem of a bunch of grapes: any number of third-party types hang off it and all count as local implementations. A project can define several contexts, for example ApiCtx for an HTTP layer that formats timestamps as strings and RpcCtx for an internal RPC layer that uses integer timestamps. They stay isolated at compile time with no conflict. One caveat: the local type must be a real, newly defined type, and a type alias for a foreign type will not work.

The post then covers position. The compiler scans Self first, then the trait's 1st generic parameter, then the 2nd, and so on, and no bare generic type parameter T may appear before the first local type. With an external ForeignTrait<A, B> and ForeignType, the article shows that impl ForeignTrait<MyCtx, T> for ForeignType is allowed, while impl ForeignTrait<T, MyCtx> for ForeignType is an error, as is impl ForeignTrait<MyCtx, String> for T, where a bare T appears in Self. A T wrapped in a non-fundamental concrete type such as Vec is covered, so impl ForeignTrait<Vec, MyCtx> for ForeignType is allowed; fundamental types like &T and Box do not count as covering. The practical advice for library authors: when a trait has several generic parameters and there is no strong reason otherwise, put Ctx in the first type parameter position, which avoids most surprising Orphan Rule errors for downstream generic impls.

The last visible section argues the same mechanism fixes an architecture problem: a standalone models crate in a Cargo workspace. Normally a shared models crate with a Product struct (Uuid id, DateTime created_at) must either wrap everything in NewTypes and drag in the serialization library and database drivers, or be merged back into the business-logic crate. With a generic Ctx, models can define Product with native types and implement ToJson for Product generically, with where clauses requiring Uuid: ToJson and DateTime: ToJson. Inside models, Uuid and DateTime do not implement ToJson yet and the code still compiles, because models only declares a deferred contract: whoever uses it later supplies a context that knows how to handle those types. The source text cuts off at this point.

Key facts

  • Error E0117 blocks implementing a foreign trait for a foreign type; the article's author says the Orphan Rule protects coherence, so two crates cannot give conflicting impls such as hyphenated versus raw 32-character hex output for Uuid.
  • The usual fixes both have costs: feature flags like with-uuid and with-chrono cannot cover every type and tie the dependency tree to the trait crate's releases, while NewTypes litter code with .0 and wrapping and unwrapping.
  • The proposed pattern: the library declares ToJson<Ctx = ()> and implements its basic types generically over any Ctx; users define an empty marker struct in their own crate and implement the trait for third-party types under it.
  • Under RFC 2451 a local type in the trait's generic parameters satisfies the rule, provided no bare type parameter comes before it; the author advises putting Ctx first. The local type must be newly defined, not a type alias.
  • Several contexts (ApiCtx, RpcCtx) can coexist in one project, and a standalone models crate can implement the trait generically over Ctx without depending on the serialization library's impls for Uuid or DateTime.

Why it matters

The Orphan Rule trips up almost everyone who glues two third-party crates together, and the usual answers are either a pile of feature flags in the trait's library or NewType wrappers everywhere. The article's pitch is that a single design decision on the library side, leaving a generic context parameter with a default type on the trait, lets users choose how third-party types implement it, including different behavior in different parts of one project. It also claims to loosen how a Cargo workspace can be split, since a models crate can stay free of heavy serialization or database dependencies.

Who it affects

Rust library authors who define traits meant to be implemented for types they do not own, such as serialization, database or conversion traits. Also application developers who keep wrapping uuid, url or chrono types in NewTypes just to satisfy E0117, and teams splitting a codebase into a Cargo workspace with a shared models crate.

How to use it

As a library author, add a generic parameter with a default to the trait, for example ToJson<Ctx = ()>, implement your built-in types generically over any Ctx, and put Ctx in the first generic parameter position if the trait has several. As a user, define an empty marker struct in your own crate (the article calls it MyCtx) and write impls like ToJson for uuid::Uuid under it. Use a newly defined struct, not a type alias. Keep any generic impls so that no bare type parameter T comes before the local type, or wrap T in a non-fundamental type such as Vec. For a standalone models crate, write the impl generically over Ctx with where clauses on the field types, or let a derive macro generate it.

How solid is it

The explanation rests on the Orphan Rule as described in RFC 2451, and the article gives compiling and failing impl examples for ordering. It is presented as a design pattern built on the existing rule, not as an official or recommended Rust feature. The ToJson trait and the uuid and chrono examples are illustrative; the visible text does not say that any existing serialization library already implements this design. No benchmarks, compile-time measurements or adoption numbers are given. The visible text names no author or publication date, and the article is cut off partway through the models-crate section, so any conclusion or further caveats are not covered here.

Risks and caveats

The pattern only helps where the trait author has already added the generic slot; it does nothing for existing traits without one. Placement matters: a bare generic parameter before the first local type triggers the error, and the article recommends putting Ctx first to avoid surprises for downstream generic impls. The local type must be a genuinely new type, since an alias to a foreign type fails. The article itself notes that NewType remains a useful pattern when the aim is domain meaning, hidden internals or enforced invariants, and objects only to using it purely to appease the Orphan Rule.

“In plain English, you don't get to make rules for someone else's types.”

— From the article "How to Bypass Rust's Orphan Rule" on edvong.com