二进制操作"=="不能应用于类型 X



我有一个自定义类型:

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 中,我可以使用反射。DeepEqual来做到这一点。我希望找到一种常见的方法来做 rust。

BTreeMap实现:

  • 当键和值类型都实现Eq时的 Eq 。
  • 当键和值类型都实现PartialEq时的部分 Eq。

如果您类型的所有字段都实现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
}

相关内容

最新更新