In the below example implementing either one of those traits would work. Compiler doesn't let to override the implementation for specific types.
Is there any other way to achieve this?
trait Giver<T,U> {
fn give_first(&self) -> T;
fn give_second(&self) -> U;
}
struct Pair<T,U>(T,U);
impl<T,U> Giver<T,U> for Pair<T,U> where T:Clone, U:Clone {
fn give_first(&self) -> T {
(self.0).clone()
}
fn give_second(&self) -> U {
(self.1).clone()
}
}
//works
impl Giver<i32, i32> for Pair<f32, f32> {
fn give_first(&self) -> i32 {
1
}
fn give_second(&self) -> i32 {
2
}
}
//error[E0119]: conflicting implementations of trait `Giver<f32, f32>` for type `Pair<f32, f32>`:
impl Giver<f32, f32> for Pair<f32, f32> {
fn give_first(&self) -> f32 {
1.0
}
fn give_second(&self) -> f32 {
2.0
}
}
i32
(the one that works) does not override the generic trait implementation, because the typesT
andU
in theGiver<T, U>
trait do not match the types in thePair<T, U>
: a generic that would match the implementation you give would beimpl<T, U, V, W> Giver<T, U> for Pair<V, W>
(which does indeed conflict with the working implementation). I don't think you can do what you want, but I will leave the answer to someone more knowledgeable. – Simon Doppler