How to Bypass Rust's Orphan Rule

17 points by lyxia


ghoti

To refer to this as a bypass of the orphan rule would be mistaken as it would give the impression that this is an accident or emergent property of the language. Instead this is an intentional feature of Rust that was deliberately implemented in order to relax the orphan rule and make more programs expressible. This is described in RFC 2451 and ironically the primary motivator that it mentions is to facilitate ORMs. https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html

john_austin

Man this feels like AI writing. The sort of chipper statements and unhelpful metaphors (a tree of generic types is like a bunch of grapes?..). The concept is nice, but it's rough to read.

Sorry if this isn't AI, these days it's tough to tell. :/

bakaq

This is revolutionary, holy shit. Looks extremely useful, I'm going to start using it.

apropos

This is an interesting approach for a library-level bypass of coherency restrictions -- for when you're designing a library and explicitly want to provide a default trait, but allow the user to override it explicitly if desired. I do not think the author makes a case for this being workable as a user-level bypass of coherency restrictions, however, and I don't understand why they bring up the conventional user-level orphan rule bypass of "use the newtype pattern", as such.

Wrapping one or two types is fine.

It's not, actually. To elaborate on the problem with the newtype design pattern: it is a design pattern. It has no first-class language support. Specifically, it means that the user has to either reimplement every single method on a new type, or dereference the wrapped type (the .0 mentioned in the article) whenever any method besides the new one is to be called. As always the case with design patterns, the lack of language support here (hence it being a design pattern) leads to boilerplate and verbosity. And since an external library's trait implementation is going to be implementing its trait on a specific type, the newtype pattern doesn't actually allow for slotting in your own trait impl within any other parts of the foreign library, like the "generic trait" pattern described in the article does.


As an aside, my personal gripes with Rust's coherency restrictions fall into four camps:

  1. I want to locally (+ privately) implement an unimplemented foreign trait on a foreign type.
  2. I want to locally override a foreign trait on a foreign type.
  3. I want method call syntax for an arbitrary function so as to be nicer to chain.
  4. I want the namespacing that traits provide, to have functions share a name but differ in type.

To this day, I do not understand why Rust's orphan rule prohibits #1. Allowing it wouldn't violate local coherency. Allowing it would only mean that a library update that adds an implementation of that foreign type produces a compile error. So what? A library update that changes the type signature of a function or method I am using produces a compile error, too.

That Rust prohibits #2 makes sense, although I hate it -- it is breaking coherency. However, I do constantly wish that Rust had an explicit opt-in exception for this. I want to be able to explicitly override a default Display implementation for a foreign type, and re-use all the machinery that builds atop Display, even if this implementation has extra restrictions to stay private, or whatever.

With regards to #3, that the standard library doesn't provide a blanket .apply(func, args...) bums me out.

With regards to #4, I grudgingly respect that the lack of support there forces me into the pattern of creating a new trait for whatever functionality it is that I am abstracting over, despite the verbosity.


Anyway, I think about the orphan rule a lot. It was nice to read this (even though it has annoying slop prose, presumably for translation -- I've got a translator built into my browser, buddy!), and think about it some more. The issue that the article is solving -- that you as a library author may want the user to be able to override your implementations of your traits -- never previously occurred to me.

MatejKafka

Reading this as a C# dev, it feels like a cludge to work around the fact that in Rust, you can't name a specific impl so you have no way to disambiguate between impls at the call site.

C# has extension methods, which are somewhat close in purpose (extending external types) and which are defined with a special syntax as static methods on your own static class. For a long time, I did not really understand why an extra class is needed just to extend an existing one, but the answer is exactly so that you can disambiguate which extension method you want using standard namespacing rules.

Otoh, this achieves a similar result without adding extra syntax to the language, so I guess in some sense it's more elegant? (although definitely less obvious when seen for the first time)

mplant

This is fine, but what I'd really like is something like Lean where you can name instances and choose them

pie_flavor

A practical example of a similar (but different) strategy can be found in rangemap (auto-defragmenting map of key range to value). RangeInclusiveMap requires the behavior std's Step trait would encode in order to tell when there's zero space between two nonoverlapping ranges so that they can be collapsed. But Step is unstable, so rangemap has to create its own StepLite trait and implement it for known types. You can implement it for your own type, but you're in orphan rule territory with a third party type. So RangeInclusiveMap is declared generic over K, V, StepFnsT: StepFns<K> = K. If it's StepLite, then RangeInclusiveMap<K, V> just works; but if it's not, you create a ZST and implement the trait for it. You do have to pay the penalty of several functions vanishing when you do, though; for example iter.collect::<RangeInclusiveMap<_, _>()) is unavailable.