← Sat, Nov 21 digest

How to Bypass Rust's Orphan Rule

read article ↗ hn thread ↗

Adding a generic context parameter to Rust traits lets downstream crates implement foreign traits for foreign types without breaking the orphan rule or using NewType wrappers.

read it Highly practical for Rust developers wrestling with dependency decoupling and the orphan rule, offering a clean architectural alternative to NewTypes.

summary

Rust's orphan rule prevents implementing foreign traits on foreign types to guarantee global coherence, typically forcing developers to use feature flags or verbose NewType wrappers. The author shows that adding a generic context parameter to a trait satisfies the orphan rule check because a local type is present in the parameters. This allows downstream crates to define custom conversions and capabilities for third-party types without cluttering data models. The pattern is demonstrated via the author's Kova ORM to maintain clean workspace dependency boundaries.

key points

  1. Rust's orphan rule checks generic parameters in order (Self, 1st parameter, 2nd, etc.), so placing a local type before any uncovered generic parameter satisfies the coherence check.
  2. Library authors can design extensible traits by adding a default generic parameter like Ctx = (), allowing downstream users to implement foreign traits for foreign types using a local marker struct.
  3. This pattern enables standalone models crates in Cargo workspaces to remain lightweight and free of heavy database or serialization dependencies.

who should read it

Rust developers and library authors managing complex type conversions or large workspaces.

discussion mixed

consensus

Commenters acknowledge the cleverness of the workaround but describe it as an awkward hack, noting that Rust's orphan rule remains a persistent pain point.

pushback

Some argue that alternative approaches like explicit serializer objects or closures (similar to Serde) are cleaner than embedding magic type parameters into traits.

best comment by 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 …

Suggests using an explicit serializer object or closure instead of a magic type parameter as a more natural architectural solution.

Generated by an LLM from the article and thread. Check the sources before relying on it.