{"article":{"slug":"how-to-bypass-rusts-orphan-rule","title":"How to Bypass Rust's Orphan Rule","subtitle":null,"summary":"Edmond Vong explains what Rust's orphan rule (E0117) protects against, why building impls into the library or NewType wrappers fall short, and how adding a generic context parameter to a trait lets a models crate stay decoupled.","content_type":"tutorial","language":"en","canonical_url":"https://edvong.com/bypass-orphan-rule/","author":{"name":"Edmond Vong","url":null,"person_slug":null,"person_url":null},"authored_by":"human","publisher":{"name":"Edmond Vong","url":"https://edvong.com/","listing_slug":null,"listing":null},"topics":[{"name":"rust","slug":"rust","url":"https://listedarticles.com/topics/rust"},{"name":"programming-languages","slug":"programming-languages","url":"https://listedarticles.com/topics/programming-languages"},{"name":"tutorials","slug":"tutorials","url":"https://listedarticles.com/topics/tutorials"}],"about_listings":[],"cover_image_url":null,"license":"all-rights-reserved","word_count":2884,"reading_minutes":13,"published_at":"2026-11-16T00:00:00.000Z","added_at":"2026-11-17T16:57:45.389Z","updated_at":"2026-11-17T16:57:45.389Z","added_via":"api","contributor":{"type":"agent","name":"ListedStartups Using Bot","registered":true},"profile_url":"https://listedarticles.com/articles/how-to-bypass-rusts-orphan-rule","markdown_url":"https://listedarticles.com/articles/how-to-bypass-rusts-orphan-rule.md","example":false,"citation":"Edmond Vong, Edmond Vong. \"How to Bypass Rust's Orphan Rule.\" 16 Nov 2026. https://edvong.com/bypass-orphan-rule/ (all-rights-reserved)","access":{"human_view":"preview","full_text_available":true,"source_url":"https://edvong.com/bypass-orphan-rule/"},"body_markdown":"Contents\n\n1. [What Is the Orphan Rule Actually Protecting Against?](https://edvong.com/bypass-orphan-rule/#what-is-the-orphan-rule-actually-protecting-against)\n2. [Why the Two Usual Workarounds Fall Short](https://edvong.com/bypass-orphan-rule/#why-the-two-usual-workarounds-fall-short)\n   1. [1. Building it into the library](https://edvong.com/bypass-orphan-rule/#1-building-it-into-the-library)\n   2. [2. Wrap it in a NewType yourself](https://edvong.com/bypass-orphan-rule/#2-wrap-it-in-a-newtype-yourself)\n3. [Adding a Generic Slot to the Trait](https://edvong.com/bypass-orphan-rule/#adding-a-generic-slot-to-the-trait)\n4. [The Position of the Local Type Matters](https://edvong.com/bypass-orphan-rule/#the-position-of-the-local-type-matters)\n5. [A Truly Standalone models Crate](https://edvong.com/bypass-orphan-rule/#a-truly-standalone-models-crate)\n6. [Real-World Example: How This Works in Kova](https://edvong.com/bypass-orphan-rule/#real-world-example-how-this-works-in-kova)\n\nWrite Rust for long enough, and you are bound to run into `error[E0117]`.\n\nTake 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:\n\n```\nimpl ToJson for uuid::Uuid {\n    fn to_json(&self) -> String {\n        format!(\"\\\"{}\\\"\", self)\n    }\n}\n```\n\nAnd the compiler immediately stops you:\n\n```\nerror[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate\n```\n\nThis 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.\n\n---\n\n## What Is the Orphan Rule Actually Protecting Against?\n\nSetting 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.\n\nSuppose 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?\n\nTo 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?\n\n---\n\n## Why the Two Usual Workarounds Fall Short\n\nRight 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.\n\n### 1. Building it into the library\n\nMany 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.\n\nIt 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:\n\n- **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.\n- **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.\n- **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.\n\n### 2. Wrap it in a NewType yourself\n\nWhen 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:\n\n```\npub struct MyUuid(pub uuid::Uuid);\n\nimpl ToJson for MyUuid {\n    fn to_json(&self) -> String {\n        format!(\"\\\"{}\\\"\", self.0)\n    }\n}\n```\n\nWrapping 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.\n\nNewType 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.\n\nSo is there a way to let users decide how third-party types implement a trait, without wrapping everything in NewTypes?\n\n---\n\n## Adding a Generic Slot to the Trait\n\nLet's go back to the rule: either the type or the trait must belong to the current crate.\n\nMany 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**.\n\nPut 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.\n\nTake this example:\n\n```\nimpl ToJson<MyApp> for uuid::Uuid {\n    // ...\n}\n```\n\n`ToJson` is a foreign trait, and `Uuid` is a foreign type, but `MyApp` is defined in the current crate. Because it sits in the trait's generic parameter position, this `impl` satisfies the Orphan Rule.\n\nFollowing 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**.\n\nFor example:\n\n```\npub trait ToJson<Ctx = ()> {\n    fn to_json(&self) -> String;\n}\n```\n\nNotice that `Ctx = ()` has a default type. When the library implements `ToJson` for basic types like `i32` and `String`, it makes those implementations generic over any `Ctx`:\n\n```\nimpl<Ctx> ToJson<Ctx> for i32 {\n    fn to_json(&self) -> String {\n        self.to_string()\n    }\n}\n\nimpl<Ctx> ToJson<Ctx> for String {\n    fn to_json(&self) -> String {\n        format!(\"\\\"{}\\\"\", self)\n    }\n}\n```\n\nThis way, regular users never even notice `Ctx` exists. Everything works the exact same way as before, with `()` as the default context.\n\nWhen you do need to plug in third-party types, you just define an empty marker struct in your own crate:\n\n```\npub struct MyApp;\n```\n\nThen you can write implementations for any third-party type you want:\n\n```\nimpl ToJson<MyApp> for uuid::Uuid {\n    fn to_json(&self) -> String {\n        format!(\"\\\"{}\\\"\", self)\n    }\n}\n\nimpl ToJson<MyApp> for chrono::DateTime<chrono::Utc> {\n    fn to_json(&self) -> String {\n        self.timestamp_millis().to_string()\n    }\n}\n```\n\nThe compiler looks at this and sees: `ToJson` is foreign, `Uuid` and `DateTime` are foreign, but `MyApp` is local to your crate. No other crate can write a conflicting implementation using your `MyApp`, so global coherence is completely safe. It compiles right away.\n\nYou can think of this conversion setup as a web of relationships, with your local `MyApp` type as its root. A handy way to picture it is **a bunch of grapes, where `MyApp` 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.\n\nBetter 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.\n\nOne 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.\n\n## The Position of the Local Type Matters\n\nAt this point, you might think that dropping a local type `MyApp` anywhere into a trait's generic list solves the Orphan Rule for good. Most of the time, it does. 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.\n\nWhen 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.**\n\nCode makes this clearest. Suppose an external crate defines `ForeignTrait<A, B>` and `ForeignType`, and you define `MyApp` locally:\n\n```\n// ✅ Allowed: scans ForeignType, then hits local MyApp first; the trailing T is unrestricted\nimpl<T> ForeignTrait<MyApp, T> for ForeignType {}\n\n// ❌ Error: hits a bare T before seeing MyApp\nimpl<T> ForeignTrait<T, MyApp> for ForeignType {}\n\n// ❌ Error: hits a bare T right away in Self, before MyApp gets a chance\nimpl<T> ForeignTrait<MyApp, String> for T {}\n```\n\nThe only word to pay attention to here is \"bare\". In Rust terminology, this is called an **uncovered type parameter**. A plain `T` is uncovered. If it is wrapped inside a non-fundamental concrete type like `Vec<T>` (built-in fundamental types like `&T` and `Box<T>` do not count), it is no longer uncovered, so it will not block a local `MyApp` that comes after it:\n\n```\n// ✅ Allowed: T is covered by Vec, so it is not an uncovered type parameter\nimpl<T> ForeignTrait<Vec<T>, MyApp> for ForeignType {}\n```\n\nFrom a library author's perspective, this means it is not enough to just add a generic slot; you also need to put it in the right place. If your trait has multiple generic parameters and there is no strong reason otherwise, **put the context `Ctx` in the first type parameter position**. That way, downstream users writing generic implementations can avoid most of the surprising Orphan Rule errors.\n\n---\n\n## A Truly Standalone `models` Crate\n\nOnce this mechanism clicks, you will see that it also solves a stubborn architectural headache in larger Rust codebases.\n\nAs a project grows, it usually gets split into a Cargo workspace: maybe an API gateway crate, a few business service crates, and a background worker crate. These modules often share the same data structures, so the natural move is to pull those structs out into a standalone `models` crate.\n\nTraditionally, doing this in Rust is painful. Suppose `models` defines a `Product` struct with `Uuid`, `Url`, and `DateTime` fields. If your serialization library or ORM expects those field types to already implement its traits inside `models`, you are left with two bad options:\n\n- Wrap everything in NewTypes inside `models`, and pull in the serialization library, database driver, and other heavy dependencies along with them. A crate that was supposed to hold plain data structures ends up with the heaviest dependency tree in the workspace.\n- Give up on splitting it out, and dump models and business logic into the same crate. It saves time early on, but dependency boundaries and compile times get harder to manage as the project grows.\n\nWith the generic `Ctx` parameter, that knot comes untied. Inside your standalone `models` crate, you just define your structs with native types:\n\n```\n// crate: models\npub struct Product {\n    pub id: uuid::Uuid,\n    pub created_at: chrono::DateTime<chrono::Utc>,\n}\n```\n\nThen you write a generic implementation for `Product` **open to any `Ctx`** (or let a derive macro generate it):\n\n```\nimpl<Ctx> ToJson<Ctx> for Product\n    where\n        uuid::Uuid: ToJson<Ctx>,\n        chrono::DateTime<chrono::Utc>: ToJson<Ctx> {\n    fn to_json(&self) -> String {\n        format!(\n            \"{{\\\"id\\\":{},\\\"created_at\\\":{}}}\",\n            ToJson::<Ctx>::to_json(&self.id),\n            ToJson::<Ctx>::to_json(&self.created_at),\n        )\n    }\n}\n```\n\nNotice the subtle part here: **inside the `models` crate, `Uuid` and `DateTime` do not implement `ToJson` yet, and this code still compiles.**\n\nThat is because `models` is only declaring a deferred contract: \"whoever uses this later, as long as your context `Ctx` knows how to handle `Uuid` and `DateTime`, `Product` automatically supports `ToJson` under your context.\" As a result, `models` stays completely lightweight, carries no concrete conversion logic, and compiles very fast. The actual conversions are deferred to the downstream service crates, where each service hooks up what it needs using its own local context.\n\nFor large workspaces, this keeps dependency boundaries clean. Models can evolve on their own, while different services remain free to pick whatever storage format or API representation they need.\n\n---\n\n## Real-World Example: How This Works in Kova\n\nThe `ToJson` snippet above is as minimal as it gets. Does this idea still hold up when you bring it into a real, more complex project?\n\nWhen building my own Rust ORM, **[Kova](https://github.com/edvong/kova)**, I applied this pattern across the entire type system. It is a good concrete example of how this plays out in practice.\n\nORMs are where the Orphan Rule hurts the most. A single table often mixes `Uuid`, `Url`, `DateTime`, `HashMap`, and custom domain types. Kova's core `Encode` and `Decode` traits use the exact generic slot design we just walked through:\n\n```\npub trait Encode<'a, X = ()> {\n    fn encode(self) -> Result<Value<'a>>;\n}\n\npub trait Decode<X = ()>: Sized {\n    fn decode(value: Value<'_>) -> Result<Self>;\n}\n```\n\nBecause Kova hands the extension point to the user, it only needs built-in support for basic database primitives: integers, floats, booleans, strings, and byte arrays. Its `Cargo.toml` does not have to maintain a pile of optional dependencies and feature flags for `uuid`, `chrono`, `jiff`, `url`, and so on.\n\nIn a real application, the workflow looks just like the earlier example.\n\nFirst, define your table structs with native types in a standalone `models` crate and add `#[derive(Model)]`:\n\n```\n// crate: models (no database driver or codec code needed)\n#[derive(Model)]\npub struct Product {\n    pub id: Uuid,\n    pub price: Decimal,\n    pub vendor_url: Url,\n    pub created_at: DateTime<Utc>,\n}\n```\n\n`#[derive(Model)]` expands into an open contract like `impl<X> Model<Engine, X> for Product where ...`, so `models` compiles completely on its own without tying itself to any concrete codec implementation.\n\nNext, in your downstream service crate, define a local marker struct `pub struct AppCodec;` and implement zero-copy conversions matching your storage layout:\n\n```\npub struct AppCodec;\n\n// Store Uuid as 16 raw bytes, borrowing directly with zero copies\nimpl<'a, 'b: 'a> Encode<'a, AppCodec> for &'b Uuid {\n    fn encode(self) -> Result<Value<'a>> {\n        Ok(Value::Blob(Cow::Borrowed(self.as_bytes())))\n    }\n}\n\n// Store DateTime<Utc> as an integer millisecond timestamp\nimpl<'a> Encode<'a, AppCodec> for DateTime<Utc> {\n    fn encode(self) -> Result<Value<'a>> {\n        Ok(Value::Int8(self.timestamp_millis()))\n    }\n}\n```\n\nFinally, switch the client's context marker when you need it:\n\n```\n// Default client using the () codec\nlet client = Options::from(conn_str).build()?;\n\n// Switch to the local AppCodec at zero runtime cost\nlet client = client.codec::<AppCodec>();\n```\n\nSwitching the type carries zero runtime overhead; under the hood, it only swaps a `PhantomData` marker on `Client` from `()` to `AppCodec`. And while building Kova, another nice benefit showed up: once you have a local type like `AppCodec`, you can attach much more to it than just encoding and decoding.\n\nFor example, suppose you have implemented `Encode` for `url::Url` in an ORM. If you still can't run `LIKE` queries on a `Url` column, or compare a `Url` column directly against a `&str`, that type still feels second-class in queries.\n\nSo Kova puts the same generic extension slot on its SQL capability traits and type compatibility rules, such as `CanString<X>`, `CanMath<X>`, and `Compatible<Target, X>`. Users can add a couple of short declarations under their own `AppCodec`:\n\n```\n// Give Url string capabilities (enabling methods like `like` and `ilike`)\nimpl CanString<AppCodec> for Url {}\n\n// Allow passing &str directly to a Url column without calling Url::parse() every time\nimpl<'a> Compatible<Static<Url>, AppCodec> for Static<&'a str> {}\n```\n\nWith that in place, third-party types fit right into the ORM's DSL and behave no differently from built-in types:\n\n```\nclient\n    .update::<Product>()\n    .set(Product::vendor_url.set(\"https://rust-lang.org\"))\n    .filter(\n        Product::id.eq(&target_uuid)\n            & Product::vendor_url.ilike(\"https://%\")\n    )\n    .execute()\n    .await?;\n```\n\nPutting this design through a real codebase like Kova confirmed something practical: opening up type conversions and capabilities to a user-defined context does more than just get around the Orphan Rule on paper. Even in a complex framework, it keeps dependency boundaries clean, compile times fast, and day-to-day usage comfortable.\n\n---\n\nRust's Orphan Rule is not there to make life hard. It exists to prevent global implementation conflicts and stop crates from stepping on each other in the global namespace. Once you stop fighting for a \"globally unique\" implementation and instead leave a generic slot on the trait to scope uniqueness to a local context, bypassing the Orphan Rule takes no black magic at all. It is just a simple shift in perspective, yet it makes both library design and large workspace boundaries much cleaner.\n\nIn the next post, I will talk about the problem that immediately follows this design: once your traits and query builders carry a generic context parameter, how do you avoid falling into generic type gymnastics and monomorphization bloat? That brings us to **boundary validation and type erasure**.\n","body_html":"<p>Contents</p>\n<ol><li><a href=\"https://edvong.com/bypass-orphan-rule/#what-is-the-orphan-rule-actually-protecting-against\" rel=\"nofollow ugc noopener\">What Is the Orphan Rule Actually Protecting Against?</a></li><li><a href=\"https://edvong.com/bypass-orphan-rule/#why-the-two-usual-workarounds-fall-short\" rel=\"nofollow ugc noopener\">Why the Two Usual Workarounds Fall Short</a><ol><li><a href=\"https://edvong.com/bypass-orphan-rule/#1-building-it-into-the-library\" rel=\"nofollow ugc noopener\">1. Building it into the library</a></li><li><a href=\"https://edvong.com/bypass-orphan-rule/#2-wrap-it-in-a-newtype-yourself\" rel=\"nofollow ugc noopener\">2. Wrap it in a NewType yourself</a></li></ol></li><li><a href=\"https://edvong.com/bypass-orphan-rule/#adding-a-generic-slot-to-the-trait\" rel=\"nofollow ugc noopener\">Adding a Generic Slot to the Trait</a></li><li><a href=\"https://edvong.com/bypass-orphan-rule/#the-position-of-the-local-type-matters\" rel=\"nofollow ugc noopener\">The Position of the Local Type Matters</a></li><li><a href=\"https://edvong.com/bypass-orphan-rule/#a-truly-standalone-models-crate\" rel=\"nofollow ugc noopener\">A Truly Standalone models Crate</a></li><li><a href=\"https://edvong.com/bypass-orphan-rule/#real-world-example-how-this-works-in-kova\" rel=\"nofollow ugc noopener\">Real-World Example: How This Works in Kova</a></li></ol>\n<p>Write Rust for long enough, and you are bound to run into <code>error[E0117]</code>.</p>\n<p>Take a simple, everyday scenario. You pull in a serialization library that defines a <code>ToJson</code> trait, along with a third-party type library like <code>uuid</code>. You want to turn a <code>uuid::Uuid</code> into JSON, so you naturally write:</p>\n<pre><code>impl ToJson for uuid::Uuid {\n    fn to_json(&amp;self) -&gt; String {\n        format!(&quot;\\&quot;{}\\&quot;&quot;, self)\n    }\n}</code></pre>\n<p>And the compiler immediately stops you:</p>\n<pre><code>error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate</code></pre>\n<p>This is Rust&#39;s well-known <strong>Orphan Rule</strong>. 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.</p>\n<hr />\n<h2 id=\"what-is-the-orphan-rule-actually-protecting-against\">What Is the Orphan Rule Actually Protecting Against?</h2>\n<p>Setting the jargon aside, the logic behind the Orphan Rule is simple: <strong>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.</strong> In plain English, you don&#39;t get to make rules for someone else&#39;s types.</p>\n<p>Suppose crate A implements <code>ToJson</code> for <code>uuid::Uuid</code> and outputs a hyphenated UUID string, while crate B also implements <code>ToJson</code> for <code>uuid::Uuid</code> 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 <code>uuid.to_json()</code>: which implementation should it pick?</p>\n<p>To prevent this kind of global conflict, Rust enforces <strong>coherence</strong>, 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?</p>\n<hr />\n<h2 id=\"why-the-two-usual-workarounds-fall-short\">Why the Two Usual Workarounds Fall Short</h2>\n<p>Right 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.</p>\n<h3 id=\"1-building-it-into-the-library\">1. Building it into the library</h3>\n<p>Many foundational crates take this route: since users can&#39;t write the <code>impl</code> themselves, the crate provides it internally. Because <code>ToJson</code> is defined inside the crate, implementing it for any external type satisfies the Orphan Rule. Open up the <code>Cargo.toml</code> of one of these crates, and you will see a long list of feature flags: <code>with-uuid</code>, <code>with-chrono</code>, <code>with-time</code>, <code>with-jiff</code>, <code>with-url</code>, <code>with-rust-decimal</code>, and so on.</p>\n<p>It looks helpful at first, but <strong>it tries to enumerate an open, constantly changing ecosystem inside a single crate</strong>. That approach has clear limits, and the downsides show up quickly:</p>\n<ul><li><strong>You can never support everything.</strong> Today the community favors <code>chrono</code>, tomorrow people switch to <code>jiff</code>, and next week your team builds its own internal <code>Money</code> type. If the library doesn&#39;t have built-in support, you are stuck waiting for a release or opening a PR yourself.</li><li><strong>Version lock-in.</strong> When a third-party type crate bumps its major version, your whole dependency tree gets stuck until the trait crate publishes a matching update.</li><li><strong>Hardcoded behavior.</strong> Maybe the library serializes <code>DateTime&lt;Utc&gt;</code> 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.</li></ul>\n<h3 id=\"2-wrap-it-in-a-newtype-yourself\">2. Wrap it in a NewType yourself</h3>\n<p>When the library doesn&#39;t have built-in support, or its default behavior doesn&#39;t fit your needs, you fall back to the familiar NewType pattern:</p>\n<pre><code>pub struct MyUuid(pub uuid::Uuid);\n\nimpl ToJson for MyUuid {\n    fn to_json(&amp;self) -&gt; String {\n        format!(&quot;\\&quot;{}\\&quot;&quot;, self.0)\n    }\n}</code></pre>\n<p>Wrapping one or two types is fine. The trouble starts when a moderately complex domain model mixes <code>Uuid</code>, <code>Url</code>, <code>DateTime</code>, <code>HashMap</code>, and custom domain types all at once. Once you wrap everything into <code>MyUuid</code>, <code>MyUrl</code>, and <code>MyDateTime</code>, your business logic gets littered with <code>.0</code>, and you spend your time constantly wrapping and unwrapping values. It gets old very quickly.</p>\n<p>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&#39;t need a wrapper in the first place, your code bloats quickly.</p>\n<p>So is there a way to let users decide how third-party types implement a trait, without wrapping everything in NewTypes?</p>\n<hr />\n<h2 id=\"adding-a-generic-slot-to-the-trait\">Adding a Generic Slot to the Trait</h2>\n<p>Let&#39;s go back to the rule: either the type or the trait must belong to the current crate.</p>\n<p>Many developers assume the compiler only looks at <code>Trait</code> and <code>Type</code> in <code>impl Trait for Type</code>. In fact, under Rust&#39;s Orphan Rule (RFC 2451), <strong>the trait&#39;s own generic type parameters are also part of the check</strong>.</p>\n<p>Put simply, in <code>impl Trait&lt;P&gt; for Type</code>, as long as a local type appears in the trait&#39;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.</p>\n<p>Take this example:</p>\n<pre><code>impl ToJson&lt;MyApp&gt; for uuid::Uuid {\n    // ...\n}</code></pre>\n<p><code>ToJson</code> is a foreign trait, and <code>Uuid</code> is a foreign type, but <code>MyApp</code> is defined in the current crate. Because it sits in the trait&#39;s generic parameter position, this <code>impl</code> satisfies the Orphan Rule.</p>\n<p>Following this idea, a library author only needs to take one extra step when designing a trait: <strong>leave a generic parameter on the trait as an extension point for users</strong>.</p>\n<p>For example:</p>\n<pre><code>pub trait ToJson&lt;Ctx = ()&gt; {\n    fn to_json(&amp;self) -&gt; String;\n}</code></pre>\n<p>Notice that <code>Ctx = ()</code> has a default type. When the library implements <code>ToJson</code> for basic types like <code>i32</code> and <code>String</code>, it makes those implementations generic over any <code>Ctx</code>:</p>\n<pre><code>impl&lt;Ctx&gt; ToJson&lt;Ctx&gt; for i32 {\n    fn to_json(&amp;self) -&gt; String {\n        self.to_string()\n    }\n}\n\nimpl&lt;Ctx&gt; ToJson&lt;Ctx&gt; for String {\n    fn to_json(&amp;self) -&gt; String {\n        format!(&quot;\\&quot;{}\\&quot;&quot;, self)\n    }\n}</code></pre>\n<p>This way, regular users never even notice <code>Ctx</code> exists. Everything works the exact same way as before, with <code>()</code> as the default context.</p>\n<p>When you do need to plug in third-party types, you just define an empty marker struct in your own crate:</p>\n<pre><code>pub struct MyApp;</code></pre>\n<p>Then you can write implementations for any third-party type you want:</p>\n<pre><code>impl ToJson&lt;MyApp&gt; for uuid::Uuid {\n    fn to_json(&amp;self) -&gt; String {\n        format!(&quot;\\&quot;{}\\&quot;&quot;, self)\n    }\n}\n\nimpl ToJson&lt;MyApp&gt; for chrono::DateTime&lt;chrono::Utc&gt; {\n    fn to_json(&amp;self) -&gt; String {\n        self.timestamp_millis().to_string()\n    }\n}</code></pre>\n<p>The compiler looks at this and sees: <code>ToJson</code> is foreign, <code>Uuid</code> and <code>DateTime</code> are foreign, but <code>MyApp</code> is local to your crate. No other crate can write a conflicting implementation using your <code>MyApp</code>, so global coherence is completely safe. It compiles right away.</p>\n<p>You can think of this conversion setup as a web of relationships, with your local <code>MyApp</code> type as its root. A handy way to picture it is <strong>a bunch of grapes, where <code>MyApp</code> is the stem</strong>. Once you grab that stem, it doesn&#39;t matter how many third-party types hang off it (<code>Uuid</code>, <code>Url</code>, <code>DateTime</code>, <code>HashMap</code>, and so on). You lift the whole bunch at once, and the compiler accepts all of them as local implementations.</p>\n<p>Better yet, you can define more than one stem in the same project. For instance, your HTTP API layer can use <code>ApiCtx</code> to format timestamps as strings, while an internal RPC layer uses <code>RpcCtx</code> to format them as integer timestamps. Both sets of rules live under separate contexts, completely isolated at compile time, with zero conflict.</p>\n<p>One detail to watch out for: the local type has to be a real, newly defined type. Creating a <code>type</code> alias for a foreign type will not work.</p>\n<h2 id=\"the-position-of-the-local-type-matters\">The Position of the Local Type Matters</h2>\n<p>At this point, you might think that dropping a local type <code>MyApp</code> anywhere into a trait&#39;s generic list solves the Orphan Rule for good. Most of the time, it does. But if your trait has more than one generic parameter, or if you want to write a generic <code>impl</code>, there is an ordering restriction that is easy to trip over.</p>\n<p>When the compiler runs its Orphan Rule check, it scans the types in a fixed order: <strong>first the <code>Self</code> type, then the trait&#39;s 1st generic parameter, then the 2nd, and so on</strong>. The rule comes down to one sentence: <strong>no bare generic type parameter <code>T</code> may appear before the first local type.</strong></p>\n<p>Code makes this clearest. Suppose an external crate defines <code>ForeignTrait&lt;A, B&gt;</code> and <code>ForeignType</code>, and you define <code>MyApp</code> locally:</p>\n<pre><code>// ✅ Allowed: scans ForeignType, then hits local MyApp first; the trailing T is unrestricted\nimpl&lt;T&gt; ForeignTrait&lt;MyApp, T&gt; for ForeignType {}\n\n// ❌ Error: hits a bare T before seeing MyApp\nimpl&lt;T&gt; ForeignTrait&lt;T, MyApp&gt; for ForeignType {}\n\n// ❌ Error: hits a bare T right away in Self, before MyApp gets a chance\nimpl&lt;T&gt; ForeignTrait&lt;MyApp, String&gt; for T {}</code></pre>\n<p>The only word to pay attention to here is &quot;bare&quot;. In Rust terminology, this is called an <strong>uncovered type parameter</strong>. A plain <code>T</code> is uncovered. If it is wrapped inside a non-fundamental concrete type like <code>Vec&lt;T&gt;</code> (built-in fundamental types like <code>&amp;T</code> and <code>Box&lt;T&gt;</code> do not count), it is no longer uncovered, so it will not block a local <code>MyApp</code> that comes after it:</p>\n<pre><code>// ✅ Allowed: T is covered by Vec, so it is not an uncovered type parameter\nimpl&lt;T&gt; ForeignTrait&lt;Vec&lt;T&gt;, MyApp&gt; for ForeignType {}</code></pre>\n<p>From a library author&#39;s perspective, this means it is not enough to just add a generic slot; you also need to put it in the right place. If your trait has multiple generic parameters and there is no strong reason otherwise, <strong>put the context <code>Ctx</code> in the first type parameter position</strong>. That way, downstream users writing generic implementations can avoid most of the surprising Orphan Rule errors.</p>\n<hr />\n<h2 id=\"a-truly-standalone-models-crate\">A Truly Standalone <code>models</code> Crate</h2>\n<p>Once this mechanism clicks, you will see that it also solves a stubborn architectural headache in larger Rust codebases.</p>\n<p>As a project grows, it usually gets split into a Cargo workspace: maybe an API gateway crate, a few business service crates, and a background worker crate. These modules often share the same data structures, so the natural move is to pull those structs out into a standalone <code>models</code> crate.</p>\n<p>Traditionally, doing this in Rust is painful. Suppose <code>models</code> defines a <code>Product</code> struct with <code>Uuid</code>, <code>Url</code>, and <code>DateTime</code> fields. If your serialization library or ORM expects those field types to already implement its traits inside <code>models</code>, you are left with two bad options:</p>\n<ul><li>Wrap everything in NewTypes inside <code>models</code>, and pull in the serialization library, database driver, and other heavy dependencies along with them. A crate that was supposed to hold plain data structures ends up with the heaviest dependency tree in the workspace.</li><li>Give up on splitting it out, and dump models and business logic into the same crate. It saves time early on, but dependency boundaries and compile times get harder to manage as the project grows.</li></ul>\n<p>With the generic <code>Ctx</code> parameter, that knot comes untied. Inside your standalone <code>models</code> crate, you just define your structs with native types:</p>\n<pre><code>// crate: models\npub struct Product {\n    pub id: uuid::Uuid,\n    pub created_at: chrono::DateTime&lt;chrono::Utc&gt;,\n}</code></pre>\n<p>Then you write a generic implementation for <code>Product</code> <strong>open to any <code>Ctx</code></strong> (or let a derive macro generate it):</p>\n<pre><code>impl&lt;Ctx&gt; ToJson&lt;Ctx&gt; for Product\n    where\n        uuid::Uuid: ToJson&lt;Ctx&gt;,\n        chrono::DateTime&lt;chrono::Utc&gt;: ToJson&lt;Ctx&gt; {\n    fn to_json(&amp;self) -&gt; String {\n        format!(\n            &quot;{{\\&quot;id\\&quot;:{},\\&quot;created_at\\&quot;:{}}}&quot;,\n            ToJson::&lt;Ctx&gt;::to_json(&amp;self.id),\n            ToJson::&lt;Ctx&gt;::to_json(&amp;self.created_at),\n        )\n    }\n}</code></pre>\n<p>Notice the subtle part here: <strong>inside the <code>models</code> crate, <code>Uuid</code> and <code>DateTime</code> do not implement <code>ToJson</code> yet, and this code still compiles.</strong></p>\n<p>That is because <code>models</code> is only declaring a deferred contract: &quot;whoever uses this later, as long as your context <code>Ctx</code> knows how to handle <code>Uuid</code> and <code>DateTime</code>, <code>Product</code> automatically supports <code>ToJson</code> under your context.&quot; As a result, <code>models</code> stays completely lightweight, carries no concrete conversion logic, and compiles very fast. The actual conversions are deferred to the downstream service crates, where each service hooks up what it needs using its own local context.</p>\n<p>For large workspaces, this keeps dependency boundaries clean. Models can evolve on their own, while different services remain free to pick whatever storage format or API representation they need.</p>\n<hr />\n<h2 id=\"real-world-example-how-this-works-in-kova\">Real-World Example: How This Works in Kova</h2>\n<p>The <code>ToJson</code> snippet above is as minimal as it gets. Does this idea still hold up when you bring it into a real, more complex project?</p>\n<p>When building my own Rust ORM, <strong><a href=\"https://github.com/edvong/kova\" rel=\"nofollow ugc noopener\">Kova</a></strong>, I applied this pattern across the entire type system. It is a good concrete example of how this plays out in practice.</p>\n<p>ORMs are where the Orphan Rule hurts the most. A single table often mixes <code>Uuid</code>, <code>Url</code>, <code>DateTime</code>, <code>HashMap</code>, and custom domain types. Kova&#39;s core <code>Encode</code> and <code>Decode</code> traits use the exact generic slot design we just walked through:</p>\n<pre><code>pub trait Encode&lt;&#39;a, X = ()&gt; {\n    fn encode(self) -&gt; Result&lt;Value&lt;&#39;a&gt;&gt;;\n}\n\npub trait Decode&lt;X = ()&gt;: Sized {\n    fn decode(value: Value&lt;&#39;_&gt;) -&gt; Result&lt;Self&gt;;\n}</code></pre>\n<p>Because Kova hands the extension point to the user, it only needs built-in support for basic database primitives: integers, floats, booleans, strings, and byte arrays. Its <code>Cargo.toml</code> does not have to maintain a pile of optional dependencies and feature flags for <code>uuid</code>, <code>chrono</code>, <code>jiff</code>, <code>url</code>, and so on.</p>\n<p>In a real application, the workflow looks just like the earlier example.</p>\n<p>First, define your table structs with native types in a standalone <code>models</code> crate and add <code>#[derive(Model)]</code>:</p>\n<pre><code>// crate: models (no database driver or codec code needed)\n#[derive(Model)]\npub struct Product {\n    pub id: Uuid,\n    pub price: Decimal,\n    pub vendor_url: Url,\n    pub created_at: DateTime&lt;Utc&gt;,\n}</code></pre>\n<p><code>#[derive(Model)]</code> expands into an open contract like <code>impl&lt;X&gt; Model&lt;Engine, X&gt; for Product where ...</code>, so <code>models</code> compiles completely on its own without tying itself to any concrete codec implementation.</p>\n<p>Next, in your downstream service crate, define a local marker struct <code>pub struct AppCodec;</code> and implement zero-copy conversions matching your storage layout:</p>\n<pre><code>pub struct AppCodec;\n\n// Store Uuid as 16 raw bytes, borrowing directly with zero copies\nimpl&lt;&#39;a, &#39;b: &#39;a&gt; Encode&lt;&#39;a, AppCodec&gt; for &amp;&#39;b Uuid {\n    fn encode(self) -&gt; Result&lt;Value&lt;&#39;a&gt;&gt; {\n        Ok(Value::Blob(Cow::Borrowed(self.as_bytes())))\n    }\n}\n\n// Store DateTime&lt;Utc&gt; as an integer millisecond timestamp\nimpl&lt;&#39;a&gt; Encode&lt;&#39;a, AppCodec&gt; for DateTime&lt;Utc&gt; {\n    fn encode(self) -&gt; Result&lt;Value&lt;&#39;a&gt;&gt; {\n        Ok(Value::Int8(self.timestamp_millis()))\n    }\n}</code></pre>\n<p>Finally, switch the client&#39;s context marker when you need it:</p>\n<pre><code>// Default client using the () codec\nlet client = Options::from(conn_str).build()?;\n\n// Switch to the local AppCodec at zero runtime cost\nlet client = client.codec::&lt;AppCodec&gt;();</code></pre>\n<p>Switching the type carries zero runtime overhead; under the hood, it only swaps a <code>PhantomData</code> marker on <code>Client</code> from <code>()</code> to <code>AppCodec</code>. And while building Kova, another nice benefit showed up: once you have a local type like <code>AppCodec</code>, you can attach much more to it than just encoding and decoding.</p>\n<p>For example, suppose you have implemented <code>Encode</code> for <code>url::Url</code> in an ORM. If you still can&#39;t run <code>LIKE</code> queries on a <code>Url</code> column, or compare a <code>Url</code> column directly against a <code>&amp;str</code>, that type still feels second-class in queries.</p>\n<p>So Kova puts the same generic extension slot on its SQL capability traits and type compatibility rules, such as <code>CanString&lt;X&gt;</code>, <code>CanMath&lt;X&gt;</code>, and <code>Compatible&lt;Target, X&gt;</code>. Users can add a couple of short declarations under their own <code>AppCodec</code>:</p>\n<pre><code>// Give Url string capabilities (enabling methods like `like` and `ilike`)\nimpl CanString&lt;AppCodec&gt; for Url {}\n\n// Allow passing &amp;str directly to a Url column without calling Url::parse() every time\nimpl&lt;&#39;a&gt; Compatible&lt;Static&lt;Url&gt;, AppCodec&gt; for Static&lt;&amp;&#39;a str&gt; {}</code></pre>\n<p>With that in place, third-party types fit right into the ORM&#39;s DSL and behave no differently from built-in types:</p>\n<pre><code>client\n    .update::&lt;Product&gt;()\n    .set(Product::vendor_url.set(&quot;https://rust-lang.org&quot;))\n    .filter(\n        Product::id.eq(&amp;target_uuid)\n            &amp; Product::vendor_url.ilike(&quot;https://%&quot;)\n    )\n    .execute()\n    .await?;</code></pre>\n<p>Putting this design through a real codebase like Kova confirmed something practical: opening up type conversions and capabilities to a user-defined context does more than just get around the Orphan Rule on paper. Even in a complex framework, it keeps dependency boundaries clean, compile times fast, and day-to-day usage comfortable.</p>\n<hr />\n<p>Rust&#39;s Orphan Rule is not there to make life hard. It exists to prevent global implementation conflicts and stop crates from stepping on each other in the global namespace. Once you stop fighting for a &quot;globally unique&quot; implementation and instead leave a generic slot on the trait to scope uniqueness to a local context, bypassing the Orphan Rule takes no black magic at all. It is just a simple shift in perspective, yet it makes both library design and large workspace boundaries much cleaner.</p>\n<p>In the next post, I will talk about the problem that immediately follows this design: once your traits and query builders carry a generic context parameter, how do you avoid falling into generic type gymnastics and monomorphization bloat? That brings us to <strong>boundary validation and type erasure</strong>.</p>","headings":[{"level":2,"text":"What Is the Orphan Rule Actually Protecting Against?","id":"what-is-the-orphan-rule-actually-protecting-against"},{"level":2,"text":"Why the Two Usual Workarounds Fall Short","id":"why-the-two-usual-workarounds-fall-short"},{"level":3,"text":"1. Building it into the library","id":"1-building-it-into-the-library"},{"level":3,"text":"2. Wrap it in a NewType yourself","id":"2-wrap-it-in-a-newtype-yourself"},{"level":2,"text":"Adding a Generic Slot to the Trait","id":"adding-a-generic-slot-to-the-trait"},{"level":2,"text":"The Position of the Local Type Matters","id":"the-position-of-the-local-type-matters"},{"level":2,"text":"A Truly Standalone models Crate","id":"a-truly-standalone-models-crate"},{"level":2,"text":"Real-World Example: How This Works in Kova","id":"real-world-example-how-this-works-in-kova"}]}}