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

前端 未结 2 1266
渐次进展
渐次进展 2021-01-07 19:25

I have two structs, A and B, and I want to use a HashMap. I have a piece of code like this:

use std::collec         


        
相关标签:
2条回答
  • 2021-01-07 19:45

    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).

    0 讨论(0)
  • 2021-01-07 19:59

    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.

    0 讨论(0)
提交回复
热议问题