Implementing a foreign trait for all implementors of a local trait in rust

145 views Asked by At

I have some local types, say

struct A;
struct B;

which all implement a local trait MyTrait:

pub trait MyTrait { }

impl MyTrait for A { }
impl MyTrait for B { }

Now I want to implement a standard library trait for both A and B, generically:

impl<T: MyTrait> ToString for T {
    fn to_string(&self) -> String {
        todo!()
    }
}

However, due to the orphan rule, this is not allowed:

error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
 --> src/main.rs:9:6
  |
9 | impl<T: MyTrait> ToString for T {
  |      ^ type parameter `T` must be used as the type parameter for some local type
  |
  = note: implementing a foreign trait is only possible if at least one of the types for which it is implemented is local
  = note: only traits defined in the current crate can be implemented for a type parameter

Is there a way to make this work (except macros) and if so, how? It need to implement the trait for these specific types, not some wrapper type.

0

There are 0 answers