Search code examples
rusthashmap

How can I accept a Rust HashMap with any hashing algorithm?


I'm working on a library that has a function that I would like to be able to accept a HashMap of any hashing algorithm. But when I try to call it with a particular type of HashMap, such as a FnvHashMap, the compiler complains.

pub fn func(map: HashMap<u32, u32>) {}

let map: FnvHashMap<u32, u32> = FnvHashMap::default();
func(map);
error[E0308]: mismatched types
  --> lib.rs:42:10
   |
42 |     func(map);
   |          ^^^ expected struct `RandomState`, found struct `BuildHasherDefault`
   |
   = note: expected struct `HashMap<_, _, RandomState>`
              found struct `HashMap<_, _, BuildHasherDefault<FnvHasher>>`

As FnvHashMap is only a type alias I thought this wouldn't be a problem.

I'm sure there's a way to do this, but I haven't found it yet. What's the correct way?


Solution

  • The definition of HashMap in the docs is:

    pub struct HashMap<K, V, S = RandomState> { /* fields omitted */ }
    

    RandomState is the default type, but it can be overridden with another type, including a generic. It may not be immediately clear, but most of the HashMap methods are declared in an impl block that constraints S: BuildHasher, which is the trait you need to bound it by:

    use std::hash::BuildHasher;
    
    pub fn func<S: BuildHasher>(map: HashMap<u32, u32, S>) {}