Custom hashing with hash/maphash

suggest change

The built-in map hashes keys for you, but only if the key type is comparable and only with == as the definition of equality. Sometimes you need more control:

Package hash/maphash gives you the same fast, seeded hash function the runtime uses for maps, plus (since Go 1.27) a standard interface between a hash table and its key type.

API added what it does
MakeSeed() 1.14 random seed that selects a hash function
Hash 1.14 streaming hasher: Write, WriteString, WriteByte, Sum64
Bytes(seed, b), String(seed, s) 1.19 hash a byte slice or string in one call
Comparable(seed, v) 1.24 hash any comparable value, consistent with ==
WriteComparable(h, v) 1.24 add a comparable value to a Hash
Hasher[T] 1.27 interface: Hash(*Hash, T) and Equal(T, T) bool
ComparableHasher[T] 1.27 Hasher[T] that uses ==

The hash is not cryptographic. Use crypto/sha256 when you need a hash an attacker can't reverse or collide (see Cryptography).

Hashing strings and bytes

A Seed selects one of 2^64 hash functions. The same seed and the same input always give the same uint64; a different seed gives an unrelated value:

package main

import (
	"fmt"
	"hash/maphash"
)

func main() {
	seed := maphash.MakeSeed()

	h1 := maphash.String(seed, "hello")
	h2 := maphash.String(seed, "hello")
	h3 := maphash.Bytes(seed, []byte("hello"))
	fmt.Println("same seed, same input:", h1 == h2)
	fmt.Println("String and Bytes agree:", h1 == h3)

	other := maphash.MakeSeed()
	fmt.Println("different seed:", h1 == maphash.String(other, "hello"))

	// Hash accepts the input in pieces
	var h maphash.Hash
	h.SetSeed(seed)
	h.WriteString("hel")
	h.WriteByte('l')
	h.Write([]byte("o"))
	fmt.Println("streamed equals String:", h.Sum64() == h1)

	// Reset keeps the seed
	h.Reset()
	h.WriteString("hello")
	fmt.Println("after Reset:", h.Sum64() == h1)
}
same seed, same input: true
String and Bytes agree: true
different seed: false
streamed equals String: true
after Reset: true

maphash.Hash is a streaming hasher: the result depends only on the seed and the sequence of bytes, not on how you split the bytes between calls. It implements hash.Hash64 and io.Writer, so you can also io.Copy into it or pass it to fmt.Fprintf.

The Write methods never fail. They return an error only to satisfy io.Writer and friends, so it's fine to ignore it.

String and Bytes are shortcuts for the common case and are faster than creating a Hash for a single value.

The hash is different in every process

MakeSeed returns a random seed, and a Seed can't be serialized: there's no way to recreate the same seed in another process. A zero Hash that you don't call SetSeed on picks a random seed on first use:

package main

import (
	"fmt"
	"hash/maphash"
)

var seed = maphash.MakeSeed()

func main() {
	fmt.Printf("%016x\n", maphash.String(seed, "hello"))

	var h maphash.Hash // zero Hash picks a random seed on first use
	h.WriteString("hello")
	fmt.Printf("%016x\n", h.Sum64())
}

Running it twice:

f2291244ee7c0ddc
04bea54f4fec5cbc
ad2878f67a042972
58286b3b194e00b1

This is on purpose. If hashes were predictable, an attacker who controls the keys (HTTP headers, JSON object names, form fields) could pick many keys with the same hash and turn every lookup in your table into a linear scan. This attack is called hash flooding. A random seed per table makes it impractical.

The flip side: never store a maphash value in a file or a database, never send it over the network and never use it to pick a server in a cluster. For a hash that's the same everywhere, use hash/fnv, hash/crc32 or crypto/sha256:

package main

import (
	"crypto/sha256"
	"fmt"
	"hash/fnv"
)

func main() {
	h := fnv.New64a()
	h.Write([]byte("hello"))
	fmt.Printf("fnv-1a: %016x\n", h.Sum64())

	sum := sha256.Sum256([]byte("hello"))
	fmt.Printf("sha256: %x\n", sum[:8])
}
fnv-1a: a430d84680aabd0b
sha256: 2cf24dba5fb0a30e

These print the same values on every run and on every machine.

A Seed is safe to use from multiple goroutines. A Hash is not: give each goroutine its own Hash and call SetSeed with the shared seed.

Hashing any comparable value

Before Go 1.24 maphash could only hash bytes, so hashing a struct meant encoding every field into bytes yourself. maphash.Comparable hashes any value of a comparable type, and guarantees that v1 == v2 implies Comparable(seed, v1) == Comparable(seed, v2):

package main

import (
	"fmt"
	"hash/maphash"
	"math"
)

type Point struct {
	X, Y int
}

type Person struct {
	Name string
	Age  int
}

func main() {
	seed := maphash.MakeSeed()

	// structs: equal values have equal hashes
	a := maphash.Comparable(seed, Point{1, 2})
	b := maphash.Comparable(seed, Point{1, 2})
	c := maphash.Comparable(seed, Point{2, 1})
	fmt.Println("Point{1,2} twice:", a == b)
	fmt.Println("Point{1,2} vs Point{2,1}:", a == c)

	// strings inside structs are hashed by content
	n1 := "Alice"
	n2 := string([]byte{'A', 'l', 'i', 'c', 'e'})
	fmt.Println("struct with string:",
		maphash.Comparable(seed, Person{n1, 30}) == maphash.Comparable(seed, Person{n2, 30}))

	// pointers are hashed by address, not by what they point to
	p1, p2 := &Point{1, 2}, &Point{1, 2}
	fmt.Println("p1 == p2:", p1 == p2)
	fmt.Println("hash(p1) == hash(p2):",
		maphash.Comparable(seed, p1) == maphash.Comparable(seed, p2))

	// floats follow == semantics
	fmt.Println("+0 vs -0:",
		maphash.Comparable(seed, 0.0) == maphash.Comparable(seed, math.Copysign(0, -1)))
	nan := math.NaN()
	fmt.Println("NaN vs NaN:",
		maphash.Comparable(seed, nan) == maphash.Comparable(seed, nan))

	// Comparable on a string is the same as String
	fmt.Println("Comparable(string) == String:",
		maphash.Comparable(seed, "go") == maphash.String(seed, "go"))
}
Point{1,2} twice: true
Point{1,2} vs Point{2,1}: false
struct with string: true
p1 == p2: false
hash(p1) == hash(p2): false
+0 vs -0: true
NaN vs NaN: false
Comparable(string) == String: true

The rules are exactly the rules of == (see Equality and comparison):

Like ==, it panics at run time if an interface holds a value that isn't comparable:

var v any = []int{1, 2}
maphash.Comparable(seed, v) // panic: runtime error: hash of unhashable type []int

WriteComparable and field boundaries

maphash.WriteComparable(h, v) is the streaming version: it adds v to a Hash. Use it to hash several values into one result.

There's a trap with WriteString: since the result only depends on the sequence of bytes, "Ann"+"abel" and "Anna"+"bel" are the same input. WriteComparable hashes each string as a separate value, so boundaries are preserved:

package main

import (
	"fmt"
	"hash/maphash"
)

type Name struct {
	First, Last string
}

// wrong: field boundaries are lost
func hashBad(h *maphash.Hash, n Name) {
	h.WriteString(n.First)
	h.WriteString(n.Last)
}

// right: WriteComparable hashes each string as a separate value
func hashGood(h *maphash.Hash, n Name) {
	maphash.WriteComparable(h, n.First)
	maphash.WriteComparable(h, n.Last)
}

func sum(seed maphash.Seed, n Name, f func(*maphash.Hash, Name)) uint64 {
	var h maphash.Hash
	h.SetSeed(seed)
	f(&h, n)
	return h.Sum64()
}

func main() {
	seed := maphash.MakeSeed()
	a := Name{"Ann", "abel"}
	b := Name{"Anna", "bel"}

	fmt.Println("bad: ", sum(seed, a, hashBad) == sum(seed, b, hashBad))
	fmt.Println("good:", sum(seed, a, hashGood) == sum(seed, b, hashGood))
	fmt.Println("whole struct:",
		maphash.Comparable(seed, a) == maphash.Comparable(seed, b))
}
bad:  true
good: false
whole struct: false

A collision doesn't make a hash table wrong (it compares keys with Equal after the hash matches), but systematic collisions like hashBad make it slow. If the whole struct is comparable and you want == semantics, maphash.Comparable(seed, n) is simplest.

The Hasher interface (Go 1.27)

Go 1.27 added an interface that separates a hash table from the definition of key equality:

type Hasher[T any] interface {
	Hash(*Hash, T)
	Equal(x, y T) bool
}

Hash writes a value into a maphash.Hash instead of returning an integer. The table owns the seed, so the key type can't accidentally pick a predictable hash function.

The one rule: if Equal(x, y) is true, Hash must produce the same hash for x and y. The easiest way to follow it is to reduce a value to a canonical form and use that form in both methods. For case-insensitive strings the canonical form is strings.ToLower(s):

package main

import (
	"fmt"
	"hash/maphash"
	"strings"
)

// CaseInsensitive is a Hasher[string] that ignores letter case.
type CaseInsensitive struct{}

func (CaseInsensitive) Hash(h *maphash.Hash, s string) {
	h.WriteString(strings.ToLower(s))
}

func (CaseInsensitive) Equal(x, y string) bool {
	return strings.ToLower(x) == strings.ToLower(y)
}

func hashOf[T any, H maphash.Hasher[T]](seed maphash.Seed, hasher H, v T) uint64 {
	var h maphash.Hash
	h.SetSeed(seed)
	hasher.Hash(&h, v)
	return h.Sum64()
}

type Point struct{ X, Y int }

func main() {
	seed := maphash.MakeSeed()

	var ci CaseInsensitive
	fmt.Println("Equal:", ci.Equal("Go", "GO"))
	fmt.Println("same hash:", hashOf(seed, ci, "Go") == hashOf(seed, ci, "GO"))

	var ph maphash.ComparableHasher[Point]
	fmt.Println("ComparableHasher Equal:", ph.Equal(Point{1, 2}, Point{1, 2}))
	fmt.Println("matches Comparable:",
		hashOf(seed, ph, Point{1, 2}) == maphash.Comparable(seed, Point{1, 2}))
}
Equal: true
same hash: true
ComparableHasher Equal: true
matches Comparable: true

Note that Equal uses strings.ToLower rather than strings.EqualFold. EqualFold uses Unicode case folding, which for a few characters doesn't agree with ToLower, and then two "equal" strings could have different hashes.

maphash.ComparableHasher[T] is the ready-made Hasher for ==: Hash calls WriteComparable and Equal returns x == y. A container written against Hasher[T] can then accept plain comparable keys too.

Hashers are usually empty structs: they must be stateless, with results that depend only on the arguments.

The standard library uses the same pattern: since Go 1.27 go/types has types.Hasher and types.HasherIgnoreTags, which hash and compare types.Type values by type identity.

A generic hash map with custom equality

Here's a small hash map parameterized by a Hasher. It uses a built-in map from hash value to a bucket of entries, so it only has to deal with collisions, not with growing a table:

package main

import (
	"fmt"
	"hash/maphash"
	"iter"
	"strings"
)

type entry[K, V any] struct {
	key K
	val V
}

// HashMap is a hash table whose key equality is defined by a Hasher.
type HashMap[K, V any, H maphash.Hasher[K]] struct {
	hasher  H
	seed    maphash.Seed
	buckets map[uint64][]entry[K, V]
	n       int
}

func NewHashMap[K, V any, H maphash.Hasher[K]](hasher H) *HashMap[K, V, H] {
	return &HashMap[K, V, H]{
		hasher:  hasher,
		seed:    maphash.MakeSeed(), // one seed per table
		buckets: map[uint64][]entry[K, V]{},
	}
}

func (m *HashMap[K, V, H]) hash(key K) uint64 {
	var h maphash.Hash
	h.SetSeed(m.seed)
	m.hasher.Hash(&h, key)
	return h.Sum64()
}

func (m *HashMap[K, V, H]) Set(key K, val V) {
	hv := m.hash(key)
	b := m.buckets[hv]
	for i := range b {
		if m.hasher.Equal(b[i].key, key) {
			b[i].val = val
			return
		}
	}
	m.buckets[hv] = append(b, entry[K, V]{key, val})
	m.n++
}

func (m *HashMap[K, V, H]) Get(key K) (V, bool) {
	for _, e := range m.buckets[m.hash(key)] {
		if m.hasher.Equal(e.key, key) {
			return e.val, true
		}
	}
	var zero V
	return zero, false
}

func (m *HashMap[K, V, H]) Delete(key K) {
	hv := m.hash(key)
	b := m.buckets[hv]
	for i := range b {
		if m.hasher.Equal(b[i].key, key) {
			b[i] = b[len(b)-1]
			b = b[:len(b)-1]
			if len(b) == 0 {
				delete(m.buckets, hv)
			} else {
				m.buckets[hv] = b
			}
			m.n--
			return
		}
	}
}

func (m *HashMap[K, V, H]) Len() int { return m.n }

func (m *HashMap[K, V, H]) All() iter.Seq2[K, V] {
	return func(yield func(K, V) bool) {
		for _, b := range m.buckets {
			for _, e := range b {
				if !yield(e.key, e.val) {
					return
				}
			}
		}
	}
}

// CaseInsensitive is a Hasher[string] that ignores letter case.
type CaseInsensitive struct{}

func (CaseInsensitive) Hash(h *maphash.Hash, s string) {
	h.WriteString(strings.ToLower(s))
}

func (CaseInsensitive) Equal(x, y string) bool {
	return strings.ToLower(x) == strings.ToLower(y)
}

func main() {
	headers := NewHashMap[string, string](CaseInsensitive{})
	headers.Set("Content-Type", "text/html")
	headers.Set("content-type", "application/json") // same key
	headers.Set("X-Request-Id", "42")

	v, ok := headers.Get("CONTENT-TYPE")
	fmt.Println(v, ok)
	fmt.Println("len:", headers.Len())

	headers.Delete("x-request-id")
	for k, v := range headers.All() {
		fmt.Printf("%s: %s\n", k, v)
	}
}
application/json true
len: 2
Content-Type: application/json

A few design points:

All returns an iterator, so the map works with for range. See Generics for more on type parameters and constraints.

Non-comparable keys and pointer keys

The same HashMap works with keys the built-in map rejects. A slice isn't comparable, but a Hasher can define equality as "same elements in the same order". And a *Point key can be compared by the value it points to instead of by address.

Using the HashMap type from the previous example (add "slices" to the imports):

// SliceHasher makes slices usable as keys, compared element by element.
type SliceHasher[T comparable] struct{}

func (SliceHasher[T]) Hash(h *maphash.Hash, s []T) {
	maphash.WriteComparable(h, len(s))
	for _, v := range s {
		maphash.WriteComparable(h, v)
	}
}

func (SliceHasher[T]) Equal(x, y []T) bool {
	return slices.Equal(x, y)
}

type Point struct{ X, Y int }

// PointValue compares *Point by the values of the fields, not by address.
type PointValue struct{}

func (PointValue) Hash(h *maphash.Hash, p *Point) {
	maphash.WriteComparable(h, *p)
}

func (PointValue) Equal(p, q *Point) bool {
	return *p == *q
}

func main() {
	// []string keys: not allowed in a built-in map
	routes := NewHashMap[[]string, string](SliceHasher[string]{})
	routes.Set([]string{"api", "users"}, "listUsers")
	routes.Set([]string{"api", "users", "new"}, "createUser")

	path := strings.Split("api/users", "/")
	fmt.Println(routes.Get(path))

	// *Point keys compared by value
	byValue := NewHashMap[*Point, string](PointValue{})
	byValue.Set(&Point{1, 2}, "first")
	byValue.Set(&Point{1, 2}, "second") // replaces "first"
	fmt.Println(byValue.Get(&Point{1, 2}))
	fmt.Println("len:", byValue.Len())

	// ComparableHasher gives the usual == semantics
	byAddr := NewHashMap[*Point, string](maphash.ComparableHasher[*Point]{})
	byAddr.Set(&Point{1, 2}, "first")
	byAddr.Set(&Point{1, 2}, "second") // different pointer: new key
	fmt.Println("len:", byAddr.Len())
}
listUsers true
second true
len: 1
len: 2

Two things to watch for with keys like these:

The traditional workaround for a slice key is to convert it to a string (strings.Join(path, "/")) and use a built-in map. That's fine when there's an unambiguous encoding, but it allocates on every lookup and is easy to get wrong when elements can contain the separator.

Hashing unordered collections

Some values are equal regardless of order: the tag sets {go, db, web} and {web, go, db}. Writing the elements in order would give different hashes. Instead, hash each element separately with the same seed and combine the results with an operator that doesn't depend on order, like ^ or +:

package main

import (
	"fmt"
	"hash/maphash"
	"slices"
)

// TagSet treats a []string as an unordered set of distinct tags.
type TagSet struct{}

func (TagSet) Hash(h *maphash.Hash, tags []string) {
	var accum uint64
	for _, t := range tags {
		var sub maphash.Hash
		sub.SetSeed(h.Seed()) // same hash function as the outer Hash
		sub.WriteString(t)
		accum ^= sub.Sum64() // XOR doesn't depend on order
	}
	maphash.WriteComparable(h, accum)
}

func (TagSet) Equal(x, y []string) bool {
	if len(x) != len(y) {
		return false
	}
	return slices.Equal(slices.Sorted(slices.Values(x)), slices.Sorted(slices.Values(y)))
}

func hashOf[T any, H maphash.Hasher[T]](seed maphash.Seed, hasher H, v T) uint64 {
	var h maphash.Hash
	h.SetSeed(seed)
	hasher.Hash(&h, v)
	return h.Sum64()
}

func main() {
	seed := maphash.MakeSeed()
	a := []string{"go", "db", "web"}
	b := []string{"web", "go", "db"}
	c := []string{"go", "db"}

	var ts TagSet
	fmt.Println("a, b equal:", ts.Equal(a, b), hashOf(seed, ts, a) == hashOf(seed, ts, b))
	fmt.Println("a, c equal:", ts.Equal(a, c), hashOf(seed, ts, a) == hashOf(seed, ts, c))
}
a, b equal: true true
a, c equal: false false

The sub-hash must use h.Seed(). A zero Hash without SetSeed would pick a random seed, and the same set would get a different hash every time.

XOR cancels out duplicates (x ^ x == 0), which is why TagSet assumes distinct elements. For multisets, use + instead.

Sharding with Comparable

You don't need the Hasher interface to benefit from maphash. A common use is splitting data into shards: a map protected by a mutex becomes a bottleneck when many goroutines use it, so split it into several maps, each with its own lock, and pick the shard by hashing the key:

package main

import (
	"fmt"
	"hash/maphash"
	"sync"
)

const numShards = 16

type shard[K comparable, V any] struct {
	mu sync.Mutex
	m  map[K]V
}

// ShardedMap spreads keys over several maps, each with its own lock,
// so goroutines working on different keys rarely wait for each other.
type ShardedMap[K comparable, V any] struct {
	seed   maphash.Seed
	shards [numShards]shard[K, V]
}

func NewShardedMap[K comparable, V any]() *ShardedMap[K, V] {
	s := &ShardedMap[K, V]{seed: maphash.MakeSeed()}
	for i := range s.shards {
		s.shards[i].m = map[K]V{}
	}
	return s
}

func (s *ShardedMap[K, V]) shardFor(key K) *shard[K, V] {
	return &s.shards[maphash.Comparable(s.seed, key)%numShards]
}

func (s *ShardedMap[K, V]) Update(key K, f func(V) V) {
	sh := s.shardFor(key)
	sh.mu.Lock()
	sh.m[key] = f(sh.m[key])
	sh.mu.Unlock()
}

func (s *ShardedMap[K, V]) Get(key K) V {
	sh := s.shardFor(key)
	sh.mu.Lock()
	defer sh.mu.Unlock()
	return sh.m[key]
}

type Visit struct {
	Page string
	Day  int
}

func main() {
	counts := NewShardedMap[Visit, int]()
	inc := func(n int) int { return n + 1 }

	var wg sync.WaitGroup
	for range 100 {
		wg.Go(func() {
			for day := range 7 {
				counts.Update(Visit{"/home", day}, inc)
				counts.Update(Visit{"/about", day}, inc)
			}
		})
	}
	wg.Wait()

	fmt.Println(counts.Get(Visit{"/home", 3}), counts.Get(Visit{"/about", 6}))
}
100 100

Before Go 1.24 this needed a type-specific hash function, or a K ~string constraint so the key could go through maphash.String. With maphash.Comparable it works for any comparable key, including the Visit struct. All bits of the result are uniformly distributed, so % numShards (or masking with numShards-1) is a fine way to reduce it.

The sharding is only valid inside one process, for the reasons explained above. To spread keys over servers, use a stable hash such as FNV or SHA-256.

wg.Go was added in Go 1.25; see WaitGroup.Go and errgroup.

Things to keep in mind

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents