2

I want to have a struct which has a generic parameter that is used as the key type of a HashMap which is a member variable. I also want my struct to implement Default and have the HashMap default to being empty. But this doesn't compile:

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

#[derive(Default)]
struct X<T: Hash + Eq> {
    x: HashMap<T, String>
}

impl<T: Hash + Eq> X<T> {
    fn new() -> X<T> {
        Default::default()
    }
}

fn main() {

}

It says:

error[E0277]: the trait bound `T: std::default::Default` is not satisfied
  --> src/main.rs:11:9
   |
11 |         Default::default()
   |         ^^^^^^^^^^^^^^^^ the trait `std::default::Default` is not implemented for `T`
   |
   = help: consider adding a `where T: std::default::Default` bound
   = note: required because of the requirements on the impl of `std::default::Default` for `X<T>`
   = note: required by `std::default::Default::default`

Why doesn't this work?

Adrian
  • 14,931
  • 9
  • 45
  • 70
  • 1
    This is because `#[derive]` uses incorrect bounds. You will need to implement `Default` manually. – trent Oct 31 '17 at 20:23
  • I have this same question, but I don't think the linked answer is a relevant answer, or if it is, I don't see how. This question is specifically about HashMap. `HashMap` does not have a `Default` type bound for `K`. The comment above is an answer, but I don't think that this question should be closed as a duplicate. – maackle Nov 14 '19 at 00:12

0 Answers0