How to implement a trait for all types implementing AsRef for this trait?

Hello.

I want my trait to be automatically implemented for all types implementing AsRef for this trait.

The following code fails to compile with the following error:

trait MyTrait {
    fn hello(&self);
}

impl<T: MyTrait, U: AsRef<T>> MyTrait for U {
    fn hello(&self) {
        self.as_ref().hello();
    }
}
error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates
  --> src/main.rs:21:6
   |
21 | impl<T: MyTrait, U: AsRef<T>> MyTrait for U {
   |      ^ unconstrained type parameter

Is there any other way to do it?

Thanks!

This isn't possible since there's no way to specify T when using the trait. Imagine you implement this trait for str, [u8], and Path, and then do String::new().hello(). Which hello should it call?

You could do something like this:

trait MyTrait<A> {
    fn hello(&self);
}

impl<T: MyTrait<T>, U: AsRef<T>> MyTrait<T> for U {
    fn hello(&self) {
        self.as_ref().hello();
    }
}

But this doesn't have any advantage over calling .as_ref().hello() when you use the trait.

4 Likes