Why does compiler say Hash is not implemented when I put a HashMap in my struct?

292 views Asked by At

I'm trying to use a HashMap in a very basic way in my struct and I'm confounded by this error ... what am I missing?

error[E0277]: the trait bound `HashMap<&str, &T>: Hash` is not satisfied
   --> src/file.rs:290:5
    |
282 | #[derive(PartialEq, Eq, Hash)]
    |                         ---- in this derive macro expansion
...
290 |     enums: &'a HashMap<&'a str, &'a T>,
    |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Hash` is not implemented for `HashMap<&str, &T>`
    |
    = note: required for `&HashMap<&str, &T>` to implement `Hash`
    = note: this error originates in the derive macro `Hash` (in Nightly builds, run with -Z macro-backtrace for more info)

Sample Rust Playground: link

&str should have all the traits implemented for it yes/no?

Here is the sample-code I'm using to show this issue:

    use std::collections::HashMap;
    use std::hash::Hash;

    trait Pt<'a> {
        fn is_int(&self) -> bool;
    }

    #[derive(PartialEq, Eq, Hash)]
    struct Enumeration<'a, T: Pt<'a>>
    where
        T: ?Sized + Eq + Hash,
    {
        pt: &'a T,
        max_length: u8,
        enum_name: &'a str,
        enums: &'a HashMap<&'a str, &'a T>,
        reverse_enums: HashMap<&'a T, &'a str>,
    }
1

There are 1 answers

2
Aleksander Krauze On

This error is about HashMap itself not implementing the Hash trait. Which it doesn't, no matter the types of keys and values. And since when you #[derive(Hash)] for a struct it requires that all it's elements also implement Hash you cannot do it for your outer struct.

You can either resign from implementing Hash for Enumeration, or you have to do it manually.