比较 `Foo<i32>` 和 `Foo<u32>`

Compare `Foo<i32>` and `Foo<u32>`

需要实现比较Foo<i32>Foo<u32>的可能性。

struct Foo<T> {
    id: usize,
    data: T
}
impl<T> Foo<T> {
    fn new_i32(i: i32) -> Foo<i32> {
        Foo {
            id: 0,
            data: i
        }
    }
    fn new_u32(u: u32) -> Foo<u32> {
        Foo {
            id: 1,
            data: u
        }
    }
}

问题是特征PartialEq只能比较相同类型。

impl<T> PartialEq for Foo<T> {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

这不起作用:

let a = Foo::new_u32(123);
let b = Foo::new_i32(123);
println!("{}", a == b);

完整代码在play.rust-lang.org

The problem is that trait PartialEq can only compare the same types.

事实并非如此。它只是将 Rhs 默认为与 Self:

相同的类型
pub trait PartialEq<Rhs = Self> where Rhs: ?Sized {
    ...
}

以下是如何为 Foo<L> 实施 PartialEq 和为任何 LR 实施 Foo<R>:

impl<L, R> PartialEq<Foo<R>> for Foo<L> {
    fn eq(&self, other: &Foo<R>) -> bool {
        self.id == other.id
    }
}

请注意,我还必须更改 impl 块以修复一些类型推断错误。最终代码:

struct Foo<T> {
    id: usize,
    data: T,
}

impl Foo<i32> {
    fn new_i32(i: i32) -> Foo<i32> {
        Foo { id: 0, data: i }
    }
}

impl Foo<u32> {
    fn new_u32(u: u32) -> Foo<u32> {
        Foo { id: 1, data: u }
    }
}

impl<L, R> PartialEq<Foo<R>> for Foo<L> {
    fn eq(&self, other: &Foo<R>) -> bool {
        self.id == other.id
    }
}

fn main() {
    let a = Foo::new_u32(123);
    let b = Foo::new_i32(123);
    println!("{}", a == b);
}

输出:

false

https://play.rust-lang.org/?gist=51166880a9ab0c49d7650588c4ed8290&version=stable&backtrace=0