How to Bypass Rust's Orphan Rule edvong.com · 14 points · 2 comments · HN thread...

@best

How to Bypass Rust's Orphan Rule edvong.com · 14 points · 2 comments · HN thread

TL;DR The author argues that Rust's Orphan Rule can be sidestepped without NewType wrappers by giving a trait a generic context parameter, such as ToJson<Ctx = ()>, and having users implement it for foreign types using a local marker struct like MyCtx. The article also covers the ordering rules for uncovered type parameters and shows the pattern applied in the author's Rust ORM, Kova.

  • The Orphan Rule (RFC 2451) counts the trait's generic parameters as well as Self, so a local type placed in a trait's generic slot lets impl ForeignTrait for ForeignType compile.
  • Library authors add a defaulted generic parameter (e.g. Ctx = ()) to the trait and make built-in impls generic over it, so ordinary users never see it.
  • Users define an empty local marker struct and implement the trait for uuid::Uuid, DateTime and other foreign types under it; separate contexts such as ApiCtx and RpcCtx can coexist.
  • Ordering matters: an uncovered bare type parameter T before the first local type triggers E0117, while T wrapped in a type like Vec is allowed; the local type should go first in the trait's parameter list.
  • A standalone models crate can declare generic impls with where-clauses (uuid::Uuid: ToJson) and stay free of serialization or database dependencies, with concrete conversions supplied downstream.
  • The author's ORM Kova uses this for Encode and Decode traits and for SQL capability traits, so built-in support is limited to primitives and third-party types are plugged in per codec.

Discussion The thread is very short, with only two top-level comments. One commenter asks whether the technique is essentially a form of named impls, which is a question about whether the pattern is a known idea under another name. The other calls it an absurd and horrifying hack and hopes library authors adopt it immediately. The mood is skeptical and wry, with no substantive replies visible.

  • Pattern is a hack, though a clever one (some): One commenter calls the technique absurd and horrifying but says library authors should adopt it. The tone is half-joking and half-critical, implying that it works but is unidiomatic.
  • Resembles named or scoped impls (a few): One commenter asks whether the generic context parameter is essentially a way of encoding named impls. This frames the article's idea in terms of a long-discussed Rust proposal rather than presenting it as new.

#rust #orphanRule #traits #ORM #typeSystem