检查自定义结构的相等性 [英] Checking equality of custom structs

查看:48
本文介绍了检查自定义结构的相等性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查两个(功能相同的)结构的相等性.

I'm trying to check equality of two (functionally identical) structs.

#[derive(PartialEq, Debug)]
pub struct TypeA<'a>(&'a str);

#[derive(PartialEq, Debug)]
pub struct TypeB<'a>(&'a str);

impl<'a> TypeA<'a> {
    pub fn new(n: &str) -> TypeA {
        TypeA(n)
    }
}

impl<'a> TypeB<'a> {
    pub fn new(n: &str) -> TypeB {
        TypeB(n)
    }
}

fn main() {
    assert_eq!(TypeA::new("A"), TypeB::new("A"));
}

它返回错误:

error[E0308]: mismatched types
  --> src/main.rs:20:5
   |
20 |     assert_eq!(TypeA::new("A"), TypeB::new("A"));
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `TypeA`, found struct `TypeB`
   |
   = note: expected type `TypeA<'_>`
              found type `TypeB<'_>`
   = note: this error originates in a macro outside of the current crate

似乎推导 PartialEq 不起作用.是在这两种类型之间手动实现它的唯一解决方案吗?问题完全在其他地方吗?

It seems like deriving PartialEq isn't working. Is the only solution to implement it manually between these two types? Is the problem somewhere else entirely?

推荐答案

Deriving PartialEq 确实有效;但是 Rust 没有不同类型的结构相等的概念.如果您在一种类型上编写 #[derive(PartialEq)],这并不意味着该类型的值可以与另一种类型的值进行比较,即使它具有相同的内部结构.这只意味着这种类型的值可以在它们之间进行比较.

Deriving PartialEq does work; but Rust does not have a notion of structural equality of different types. If you write #[derive(PartialEq)] on one type, it does not mean that values of this type could be compared with values of another type, even if it has the same internal structure. It only means that values of this type can be compared between themselves.

然而,PartialEq 有一个右侧操作数的类型参数(创造性地命名为 Rhs),这意味着您可以实现 PartialEq对于具有不同类型参数的单个类型多次.#[derive(PartialEq)] 只会在应用在 X 上时实现 PartialEq,但这并不妨碍你实现 PartialEq 用于 Y 自己的其他值.

However, PartialEq has a type parameter for the right-hand side operand (creatively named Rhs), which means you can implement PartialEq multiple times for a single type with different type arguments. #[derive(PartialEq)] will only implement PartialEq<X> when applied on X, but that doesn't stop you from implementing PartialEq<Y> for other values of Y yourself.

在这种情况下,您需要为这些类型手动实现 PartialEq,双向:

In this case, you do need to implement PartialEq manually for these types, in both directions:

impl<'a, 'b> PartialEq<TypeB<'b>> for TypeA<'a> {
    fn eq(&self, other: &TypeB<'b>) -> bool {
        self.0 == other.0
    }
}

impl<'a, 'b> PartialEq<TypeA<'a>> for TypeB<'b> {
    fn eq(&self, other: &TypeA<'a>) -> bool {
        self.0 == other.0
    }
}

之后,您将能够对这些类型对使用 ==assert_eq!().请记住,如果您也需要,您仍然可以在类型上保留 #[derive(PartialEq)]

Afterwards you will be able to use == or assert_eq!() for these pairs of types. Remember that you can still keep #[derive(PartialEq)] on your types if you need it too!

这篇关于检查自定义结构的相等性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆