Trait Wrapper on Orphan Rule

Advanced Traits - The Rust Programming Language

The Orphan Rule in Rust is a part of the trait coherence system that ensures type safety and prevents conflicting trait implementations. According to the Orphan Rule, you can only implement a trait for a type if either the trait or the type is local to your crate1. This means you cannot implement external traits on external types.

However, there’s a common workaround called the Trait Wrapper pattern, also known as the Newtype pattern, which allows you to get around the Orphan Rule. The idea is to create a new type in your local crate that wraps the external type, and then you can implement any trait on this new wrapper type because it is considered local to your crate

Here’s an example of how you might use this pattern:

// External type and trait
extern crate some_library;
use some_library::{SomeType, SomeTrait};

// Your local wrapper type
struct MyWrapper(SomeType);

// Implementing the external trait on your wrapper type
impl SomeTrait for MyWrapper {
    // methods go here
}

In this example, SomeType is a type from an external crate, and SomeTrait is a trait from the same external crate. You cannot directly implement SomeTrait for SomeType because of the Orphan Rule. However, by creating MyWrapper, a new type that wraps SomeType, you can implement SomeTrait for MyWrapper since it’s local to your crate.

This pattern is widely used in Rust to extend the functionality of types from external libraries without violating the Orphan Rule.