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.

String Compare Equivalent vs Partial Equivalent

Before we proceed, let us differentiate between Equivalent and Partial Equivalent. When two struct instances to be equivalent across all corresponding field values, they are Equivalent. On the other hand, when two struct instance is equivalent across only some field values, they are Partial(ly) Equivalent. In Rust, Equivalent and Partial Equivalent are generally represented by the traits Eq and PartialEq, respectively.

How To Compare Equivalent Instances in Rust

Let us say we have the following struct to represent a point in an X-Y graph. In this case, two (2) points are the same if and only if they have the same values for x and y.

To make two Point instance equivalent, we need to modify the struct to:

That is all! We can now test with some data.

Why two Traits?

Now, why are we using two traits? As of Rust 1.37.0, PartialEq is required for Eq.




Partial(ly) Equivalent Instances in Rust

Student Struct

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

We need to implement the PartialEq trait.




And that is how we compare two struct Instances using traits in Rust!

For more example, please read  Check if key exists in HashMap Examples. There are example codes 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? Please visit our Facebook page!

You Might Also Like