How to implement Eq and Hash for my own structs to use them as a HashMap key?

This is how the Rust documentation says you write your own implementation of Hash:

use std::hash::{Hash, Hasher};

struct Person {
    id: u32,
    name: String,
    phone: u64,
}

impl Hash for Person {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.id.hash(state);
        self.phone.hash(state);
    }
}

Source: https://doc.rust-lang.org/std/hash/trait.Hash.html


Eq is what we call a marker trait: it has no method on its own, it is just a way for the programmer to express that the struct verifies a certain property. You can implement it like this:

impl Eq for Application {}

Or alternatively, use #[derive(Eq)] on top of the Application declaration

Eq is a trait bound by PartialEq. This means that you can implement it only on structs that also implement PartialEq (which is the case here). By implementing Eq, you make the promise that your implementation of PartialEq is reflexive (see the docs for what it means).


You can have the compiler derive these instances for you by inserting the following before your struct declaration:

#[derive(PartialEq, Eq, Hash)]
pub struct A {
    // ...
}

You could also implement them manually instead. If you want to do that, you should read the documentation on traits, Eq and Hash.

Tags:

Hashmap

Rust