Start learning free

LESSON 615 OF 642 · OBJECT-ORIENTED PROGRAMMING

Comparing Objects in Rust in Rust

Lesson

TL ; DR:

Rust can't compare two values of your struct until you say how. A derive line above the struct writes that code for you. Then == compares the fields, and the struct can go in a HashSet.


#[derive(PartialEq, Eq, Hash)]
struct Time {
    hour: i32,
    minute: i32,
}


Full lesson:

Write a == b for two Time values, and the code doesn't compile. Rust has no default == for a struct. It won't guess which fields matter.

Traits for equality

== and != come from the trait PartialEq. Eq adds a promise that every value equals itself.

A HashSet needs Eq and Hash. Hash turns a value into a number. The set files each value under that number, then compares only values with the same one.

derive

You could implement the three traits by hand. For field-by-field equality, derive writes them. Put #[derive(PartialEq, Eq, Hash)] right above the struct.

Every field needs these traits too. Integers and strings have them.

Inserting moves the value

insert moves a value into the set. If an equal value is there, the set keeps one. So the code compares a, b and c before it inserts them.


Your task

The Time struct keeps an hour and a minute. Derive PartialEq, Eq and Hash for it. Then create alarms, an empty HashSet.

main_function compares three times. Then it inserts them into alarms.

Expected output:

a and b are the same time
a and c are different times
alarms: 2
STEP 1 OF 2
    Ctrl + Enter to check

    Comparing Objects in Rust

    Keep going with Rust500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free