0

Suppose I want to write a HashMap wrapper. My attempt:

struct Wrapper<K,V> where HashMap<K,V>: Default{
   value: HashMap<K,V>
}

I want K,V to implicitly have whatever bounds that make HashMap<K,V> valid. Is there a trait that is better than Default that better communicates this intention? Something like HashMap<K,V>: True ?

Gnut
  • 541
  • 1
  • 5
  • 19

1 Answers1

5

HashMap is valid, type-wise, for any key/value types. You can call HashMap::new with any types.

Obviously this isn't very useful, but there's no type-level usefulness measure, so you can't work around copying the trait bounds. Nearly all of HashMap's methods are in this impl block, so you can just copy the bounds of that one.

where K: Eq + Hash

You should put this only on the impl block that requires it and not on the struct, if possible. See this question for an explanation. You may also need to put bounds on each method, like what HashMap does.

where
    K: Borrow<Q>,
    Q: Hash + Eq + ?Sized,
drewtato
  • 6,783
  • 1
  • 12
  • 17