I want to override trait of external crate

#1

Hello.

I want to override trait implement of external crate.

In crate A,

trait Ta {
    fn a();
}

impl Ta for TypeA {
    fn a() {
       ...
    }
}

In my crate
I want to modify the behavior of fn a.

extern crate A;

implement Ta for TypeA {
    fn a() {
        ....
    }
}

can’t be a solution.
How to override fn a

Thanks in advance.

0 Likes

#2

You can’t re-impl traits on a type, and you can’t impl foreign traits on foreign structs. You can impl your own traits on foreign structs or vice-versa but both cannot be foreign.

0 Likes

#3

As @OptimisticPeach mentioned, this is deliberately not possible. Only one crate can implement each trait/type combination. Otherwise there could be chaos caused by dependencies overwriting and breaking each other.

The workaround is usually to wrap the type in a newtype, i.e. your own struct

struct MyWrapper(NotMyType);
impl NotMyTrait for MyWrapper {}
0 Likes

#4

Thanks! I fully understand it.

0 Likes