Rust – How to Compare Struct Instances

Last Updated on

In Rust, we can compare if two struct instances are equivalent and whose corresponding field values are the same.

Equivalent vs Partial Equivalent

Before we proceed, let us differentiate between Equivalent and Partial Equivalent. When two (2) struct instances to be equivalent across all corresponding field values, they are Equivalent. On the other hand, when two (2) 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.

Equivalent Instances

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 mocked 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

Student Struct

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

We need to implement the PartialEq trait.





Karl San Gabriel

Professional Software Developer