Rust's Orphan Rule Has a Backdoor: Add a Generic Slot to Your Trait

How to Bypass Rust's Orphan Rule

Rust's orphan rule blocks implementing foreign traits for foreign types, but a little-known RFC 2451 loophole lets you bypass it by adding a generic context parameter to the trait. Library authors can define `trait ToJson<Ctx = ()>`, and users can then implement it for any third-party type using a local marker struct like `MyCtx`. This avoids NewType wrapping and feature-flag bloat, and even enables a clean standalone `models` crate with no heavy dependencies.

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.
  1. i2talics

    The author is going towards the right solution but their solution has things flipped, and the result feels like a hack. What I would suggest is instead of implementing a trait with a magic type parameter, you should instead solve this by providing an object that dispatches the trait method rather than dispatching it from the target type.

    That is, instead of "trait ToJson { fn to_json(&self) -> Json }" you should have "trait JsonSerializer<T> { fn to_json(&self, what: &T) -> Json }". Now we can implement "impl JsonSerializer<Date> for ISO8601" and "impl JsonSerializer<Date> for TimestampSeconds".

    If this seems a little wordy, realize that actually we've just reimplemented Rust's closures as our own custom trait. So we could just use closures: "JsonSerializer<T>" is the same thing as the trait "Fn(&T) -> Json". This is exactly what serde features, as you can pass in a serializer function rather than using the type itself to look up the behavior[1].

    One other place this commonly comes up for me is in comparisons. Some types, like strings, don't have a single universal way to compare them. This means that Ord is insufficient. The solution is to have a "comparator" trait that provides the ordering. Again, this could also just be a closure with two arguments.

    [1]: https://serde.rs/field-attrs.html#serialize_with

  2. reallyreason

    Isn’t this essentially a form of, or encoding of, named impls?

  3. hyperman1

    While I think rust is one of the best languages today, this is a corner where it reminds me of C++: Here is a rule with lots of tiny special cases, it has painful consequences in the real world, and if everyone adds some 'best practice' magic to their code, we have 90% of a solution.

More from this day

2026-11-21