Reuse trait implementation of other type

Say I have a struct TheirStruct (maybe in an external crate) that implements the traits Foo and Bar.

I want to create a struct MyStruct that uses the implementation for Foo from TheirStruct and has its own implementation for Bar. Or in other words I want MyStruct to be like a type alias of TheirStruct. I just want to override the Bar trait implementation of TheirStruct.

Any way to do this?

There's no builtin automatic way to forward trait implementations. There are crates that might hide some of the boilerplate.
You can implement it yourself.
Make MyStruct a wrapper around TheirStruct:

struct MyStruct(TheirStruct);

Then implement Foo on it and forward to the TheirStruct member and implement Bar they way you want it.

I guess you could also implement Deref<Target=TheirStruct> for MyStruct and thus benefit from auto-dereferencing in some cases.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.