I would like to write PartialEq for my struct holding a generic type. I'd like the comparison to fail when the types are not equal in both structs and do an actual comparison when they are equal. Is this possible to do?
Here is the code:
fn main() {
let first = Foo { inner: 0_u32 };
let second = Foo { inner: 0_u32 };
let third = Foo { inner: "text" };
println!("{}", first == second); // print true
println!("{}", first == third); // print false
}
struct Foo<T> {
inner: T
}
impl<T> PartialEq<T> for Foo<T>
where T: PartialEq
{
fn eq(&self, other: &T) -> bool {
self.inner == other.inner
}
}
impl<T, U> PartialEq<U> for Foo<T>
{
fn eq(&self, other: &U) -> bool {
false
}
}
This produces an error of conflicting PartialEq
implementations. Is there a way to achieve what I want?
As Chaiym mentions in the comments this can only be done on nightly with #![feature(specialization)]
:
#![feature(specialization)]
//…
impl<T, U> PartialEq<Foo<U>> for Foo<T>
where
T: PartialEq<U>,
{
fn eq(&self, other: &Foo<U>) -> bool {
self.inner == other.inner
}
}
impl<T, U> PartialEq<U> for Foo<T> {
default fn eq(&self, _: &U) -> bool {
false
}
}