二元运算符`==`不能应用于类型X。

21

我有一个自定义类型:

pub struct PValue {
    pub name: String,
    pub value: Option<serde_json::Value>,
    pub from: Option<String>,
}
pub struct CC {
    pub name: String,
    pub inst_name: String,
    pub pv: Option<Vec<PValue>>,
}

pub struct ComponentRecord {
    config: CC,
    version: String,
}

let cr = ComponentRecord {
        version: "123".to_string(),
        config: CC {
            name: "n123".to_string(),
            instance_name: "inst123".to_string(),
            pv: None,
        },
    };
let newcr = ComponentRecord {
        version: "123".to_string(),
        config: ComponentConfiguration {
            name: "n123".to_string(),
            instance_name: "inst123".to_string(),
            pv: None,
        },
    };
assert_eq!(crgot, cr);

然后我遇到了错误:

error[E0369]: binary operation `==` cannot be applied to type `&ComponentRecord`
  --> src/xxx_test.rs:39:5
   |
39 |     assert_eq!(crgot, cr);
   |     ^^^^^^^^^^^^^^^^^^^^^^
   |     |
   |     ComponentRecord
   |     ComponentRecord
   |
  = note: an implementation of `std::cmp::PartialEq` might be missing for `&ComponentRecord`

我应该如何测试两个RecordAnnotation实例是否相等?

我在编写测试,因此不关心性能是否良好。

在golang中,我可以使用reflect.DeepEqual来完成。 我希望在Rust中找到一种通用的方法。


你尝试了什么?一个简单的比较可以很好地工作!record1 == record2 - Boiethios
事实上,我的自定义类型比那个更复杂,让我修改一下我的问题,谢谢。 - wonderflow
1个回答

19

BTreeMap实现:

  • 当键和值类型都实现Eq时,Eq
  • 当键和值类型都实现PartialEq 时,PartialEq

如果您的类型的所有字段都实现了PartialEq,则可以轻松地为整个结构派生PartialEq:

#[derive(PartialEq)]
pub struct ComponentRecord {
    config: String,
    version: String,
}

然后你就可以在你的映射中简单使用==运算符:
pub type RecordAnnotation = BTreeMap<String, ComponentRecord>;

fn compare (a: &RecordAnnotation, b: &RecordAnnotation) -> bool {
    a == b
}

我该如何实现 Option<Vec<PValue>> 的 PartialEq? - wonderflow
5
我已经理解了,只需在类型PValue之上添加PartialEq即可。 - wonderflow

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接