What is the correct way to compare Structs?

There are several methods that I know of.

  1. Via #derive[(PartialEq)]
  2. Compare fields myself, or specific field(s): a.name == b.name

Are there other means to do this (like via a hash or something)?
How do I know I am not comparing 2 similar items but different memory locations?

The #[derive(PartialEq)] will make the == operator work for comparing the struct. This is a comparison of the value, and not of object identity, so two different memory locations holding the same value will return true.

If you want to compare object identity, then you want something along the lines of Arc::ptr_eq.

3 Likes

Rust doesn't compare by pointers. Objects in Rust generally don't have an identity, and don't even have a stable address.

Even when you compare a struct with itself, a == a, it will run partial_cmp that typically checks all fields for semantic equality of the values, and it could even result in false being returned the struct contains NaN anywhere.

6 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.