Why does Rust prevent implementing an external trait for an external struct?

Viewed 1548

I just came across the problem of implementing a trait I do not own for a type I do not own. Then I googled the exact How do I implement a trait I don't own for a type I don't own? question.

The thing that confused me is the motivation behind such restriction. I came from Scala where it is possible to have an external typeclass instance for an external type.

Why does Rust restrict that?

2 Answers

I just read the Rust Book's chapter about implementing traits and, as @AlexLarionov suggested in the comment that it would be impossible to choose an appropriate implementation:

But we can’t implement external traits on external types. For example, we can’t implement the Display trait on Vec<T> within our aggregator crate, because Display and Vec<T> are defined in the standard library and aren’t local to our aggregator crate. This restriction is part of a property of programs called coherence, and more specifically the orphan rule, so named because the parent type is not present. This rule ensures that other people’s code can’t break your code and vice versa. Without the rule, two crates could implement the same trait for the same type, and Rust wouldn’t know which implementation to use.

As Alexey Larionov explains in the comments, if two crates could implement a trait for the same struct there would be a conflict of which trait implementation to use. With this restriction, Rust guarantees that every (struct, trait) pair will have at most one implementation across all crates.

If you find yourself needing to implement an external trait for an external struct you can leverage the Rust New Type Idiom.

By wrapping an external struct in a new type you are able implement any external trait on that new type.

While the new type won't be the same as the external struct, you can reference that wrapped type with the .0 syntax, as explained in the New Type Idiom documentation.

Related