Rust, Software Development

Rust – How to Compare Struct Instances With Traits

In Rust, we can compare if two struct instances are equivalent and whose respective field values are the same. However, doing so requires using traits.

Equivalent vs. Partial Equivalent

Before we proceed, let us differentiate between Equivalent and Partial Equivalent. When two struct instances are equivalent across all corresponding field values, they are Equivalent.

On the other hand, when two struct instances are equivalent across only some field values, they are Partial(ly) Equivalent. In Rust, Equivalent and Partial Equivalent are these traits –  Eq and PartialEq, respectively, and we can use them to compare struct instances.

Compare Struct Instances with Equivalent in Rust

We have the following struct to represent a point in an X-Y graph. In this case, two (2) instances of the Point struct are the same if and only if they have the same values for x and y.

To make two Rust struct Point instances equivalent when comparing them, we need to modify the struct to the following.

That is all! We can now test with some data. However, there is a problem with this technique in Rust – we cannot customize how we compare the instances. We will revisit that issue later on in this post.

Now, why are we using two traits? As of Rust 1.59.0, we need to use both Eq and PartialEq.

Let’s test some Rust codes – consider the following.

When we run these codes, we get the following output.

Compare Struct Instances with Partial(ly) Equivalent in Rust

For this purpose, we want to compare two Rust struct instances partially equivalent to student_id.

We need to implement the PartialEq trait.

Note that we are now using the Student struct for this part.


And that is how we compare struct instances using traits!

Please read  Check if a key exists in HashMap Examples for more examples. There are example codes that use struct instances as keys in HashMap. As keys, we need to compare these instances to retrieve their respective values from the HashMap instance.


Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like