I would like to use a HashSet
as the key to a HashMap
. Is this possible?
use std::collections::{HashMap, HashSet};
fn main() {
let hmap: HashMap<HashSet<usize>, String> = HashMap::new();
}
gives the following error:
error[E0277]: the trait bound `std::collections::HashSet<usize>: std::hash::Hash` is not satisfied
--> src/main.rs:4:49
|
4 | let hmap: HashMap<HashSet<usize>, String> = HashMap::new();
| ^^^^^^^^^^^^ the trait `std::hash::Hash` is not implemented for `std::collections::HashSet<usize>`
|
= note: required by `<std::collections::HashMap<K, V>>::new`
To make something the key of a
HashMap
, you need to satisfy 3 traits:Hash
— How do you calculate a hash value for the type?PartialEq
— How do you decide if two instances of a type are the same?Eq
— Can you guarantee that the equality is reflexive, symmetric, and transitive? This requiresPartialEq
.This is based on the definition of
HashMap
:Checking out the docs for
HashSet
, you can see what traits it implements (listed at the bottom of the page).There isn't an implementation of
Hash
forHashSet
, so it cannot be used as a key in aHashMap
. That being said, if you have a rational way of computing the hash of aHashSet
, then you could create a "newtype" around theHashSet
and implement these three traits on it.Here's an example for the "newtype":