HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustCritical

How do I implement a trait I don't own for a type I don't own?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
ownhowdonfortypeimplementtrait

Problem

I wanted to implement the Shl trait for Vec, the code is below. This would make things like vec ); only traits defined in the current crate can be implemented for a type parameter [E0210]

As I understand it, I'd have to patch the stdlib, more specifically the collections::vec crate. Is there another way to change this code to compile successfully?

Solution

While you can't do that exactly, the usual workaround is to just wrap the type you want in your own type and implement the trait on that.

use somecrate::FooType;
use somecrate::BarTrait;

struct MyType(FooType);

impl BarTrait for MyType {
    fn bar(&self) {
        // use `self.0` here
    }
}

Code Snippets

use somecrate::FooType;
use somecrate::BarTrait;

struct MyType(FooType);

impl BarTrait for MyType {
    fn bar(&self) {
        // use `self.0` here
    }
}

Context

Stack Overflow Q#25413201, score: 125

Revisions (0)

No revisions yet.