I'd like to implement a trait for some values (like MyType) and their references (&MyType). I tried to solve this by using the Borrow trait.
use std::borrow::Borrow;
trait MyTrait {}
impl<B> MyTrait for B where B: Borrow<bool> {}
impl<B> MyTrait for B where B: Borrow<usize> {}
fn main() {
}
This fails, because a struct might implement both traits. Is there a proper way to solve this or do I have to write each implementation for both variants?
I just tried to solve this by implementing the trait for the reference variant and adding a generic trait implementation that should add the value variant for all existing reference variant implementations:
impl<'a> MyTrait for &'a bool
impl<'a, T> MyTrait for T where &'a T: MyTrait
But the compiler still says that they are conflicting and I don't know why.
This is how my current implementation looks like. But since the implementation of bool and &bool are exactly the same, I wonder if I can somehow avoid to write two implementations for each type. The code gets quite messy when double-implementing the trait for about 20 types.
The implementation is different between different types. It's only the same between Type and &Type. But yes, a macro would be an option. I just wanted to know if there is a less complex solution and why my attempt to solve this doesn't work.
error[E0275]: overflow evaluating the requirement
= note: required because of the requirements on the impl of `MyTrait` for `&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'a T`
= note: required because of the requirements on the impl of `MyTrait` for `&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'a T`
= note: required because of the requirements on the impl of `MyTrait` for `&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'a T`
...
= note: required because of the requirements on the impl of `MyTrait` for `&'a T`
note: required by `MyTrait`
Sorry everyone for the late reply, but do you think there is a way to do this for standard library traits? Also is it possible that this solution results in dynamically dispatched methods? If so, perhaps the macro solution discussed earlier is better.