如果类型参数T实现了PartialEq,我如何比较泛型结构?我尝试了以下方法,但它没有编译。我知道我可以让Foobar<T>派生Eq等等,但是Foobar是否有可能“继承”或者以某种方式从T继承PartialEq呢?我猜类似的东西已经为Vec做了,例如,您可以比较Vec的当且仅当T实现了PartialEq。
struct Foobar<T> {
    foobar: T
}
fn x() -> bool {
    let a = Foobar{foobar: 1};
    let b = Foobar{foobar: 2};
    a == b
}发布于 2021-10-10 08:40:40
当T是PartialEq时,您也可以通过约束实现来实现这个特性:
impl<T> PartialEq for Foobar<T> where T: PartialEq {
    fn eq(&self, other: &Self) -> bool {
        self.foobar == other.foobar
    }
}尽管最简单的解决办法是直接导出:
#[derive(PartialEq)]
struct Foobar<T> {
    foobar: T
}它还会使您的内部类型受到该特性的约束,这意味着您将无法用非Foobar的内容实例化一个PartialEq结构。
#[derive(PartialEq)]
struct Foobar<T> {
    foobar: T
}
struct NonPartialEq {}
fn main() {
    let a = Foobar{foobar: NonPartialEq {}};
    let b = Foobar{foobar: NonPartialEq {}};
    assert!(a != b)
}这样的内容不会用以下方法进行编译:
error[E0369]: binary operation `!=` cannot be applied to type `Foobar<NonPartialEq>`
  --> src/main.rs:11:15
   |
11 |     assert!(a != b)
   |             - ^^ - Foobar<NonPartialEq>
   |             |
   |             Foobar<NonPartialEq>
   |
   = note: an implementation of `std::cmp::PartialEq` might be missing for `Foobar<NonPartialEq>`因此,使用约束通过hanb实现它允许您对任何类型使用您的结构,但是当内部类型是这样的时候,您仍然能够使用PartialEq。
发布于 2021-10-10 08:40:23
关于Vec<_>,滚动它的文档来查看是否有一个特质实施像您想要的那样传播Eq是很有用的。
impl<T, A> Eq for Vec<T, A> where
    T: Eq,
    A: Allocator, 所以你需要做同样的事情:
struct Foobar<T> {
    foobar: T
}
impl<T> PartialEq for Foobar<T> where T: PartialEq {
    fn eq(&self, other: &Self) -> bool {
        self.foobar == other.foobar
    }
}
impl<T> Eq for Foobar<T> where T: Eq {}
fn x() -> bool {
    let a = Foobar{foobar: 1};
    let b = Foobar{foobar: 2};
    a == b
}
fn main() {
    println!("{}", x()); // false
}https://stackoverflow.com/questions/69513568
复制相似问题