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

Binary operation `==` cannot be applied to type 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 中,我可以使用 reflect.DeepEqual 来做到这一点。希望能在rust中找到通用的方法。

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
}