go

How does go calculate a hash value for keys in a map?


How does Go calculate a hash for keys in a map? Is it truly unique and is it available for use in other structures?

I imagine it's easy for primitive keys like int or immutable string but it seems nontrivial for composite structures.


Solution

  • Since Go 1.14, the go standard library provides the hash/maphash package. The hash functions in this package aren't guaranteed to be the same ones used by Go maps (but it appears that they are, which makes sense); they are guaranteed to be good functions for implementing hashmaps and the like.

    Beginning with go 1.24, hash/maphash can consume any comparable value (anything that can have == used on it; anything that could be a map key). Before that, it only operated on string and []byte, so if you wanted to get a hash for any other type you would have to serialize it yourself.