Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary operation `==` cannot be applied to type X

Tags:

equality

rust

I have a custom type:

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);

Then I got error:

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`

How could I test two RecordAnnotation instance is equal?

I was writing test for that, so I won't mind whether the performance is ok.

In golang, I can use reflect.DeepEqual to do that. I hope to find a common way to do in rust.

like image 527
wonderflow Avatar asked Sep 03 '19 12:09

wonderflow


1 Answers

BTreeMap implements:

  • Eq when both key and value types implement Eq.
  • PartialEq when both key and value types implement PartialEq.

If all fields of your type implement PartialEq, you can easily derive PartialEq for the entire struct:

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

Then you'll be able to simply use the == operator on your maps:

pub type RecordAnnotation = BTreeMap<String, ComponentRecord>;

fn compare (a: &RecordAnnotation, b: &RecordAnnotation) -> bool {
    a == b
}
like image 132
justinas Avatar answered Nov 15 '22 12:11

justinas