hash/maphash

最後更新


hash/maphash 提供帶隨機種子的快速雜湊函式,專門用來實作雜湊表、分片(sharding)、布隆過濾器這類自訂資料結構。

這個套件做什麼


Go 內建的 映射 背後就是雜湊表,但 runtime 用的雜湊函式沒有公開。當你要自己做資料結構,例如「把鍵平均分到 16 個分片,每片各有一把鎖」,就需要一個又快、分布又均勻的雜湊函式,maphash 就是把 runtime 那一套開放出來。
它和其他雜湊套件的差別在於種子(seed):
  • 每個 Seed 都是隨機產生的,同一個種子對同一個輸入永遠得到同樣的值
  • 換一個種子,結果就完全不同;每次程式重新啟動,MakeSeed 給的種子也不同
  • 種子不能序列化,也不能在另一個程序重建

所以 maphash 的值只能在同一個程序內使用,不能存到檔案或資料庫、不能跨機器比對。需要穩定、可重現的雜湊值請用 hash/fnv 或 hash/crc32;需要防竄改請用 crypto/sha256。
隨機種子的好處是攻擊者猜不到雜湊值,難以刻意製造大量碰撞把雜湊表拖慢。
本頁的範例因為種子每次不同,只印比較結果(true/false),不印雜湊值本身。

匯入


  1. import "hash/maphash"

常用 API


MakeSeed 與 String


MakeSeed() 產生一個新的隨機種子。String(seed, s) 用這個種子算出字串的 64 位元雜湊值。
注意:Seed 的零值是無效的,一定要用 MakeSeed 建立。
簽名:
  1. func MakeSeed() Seed
  2. func String(seed Seed, s string) uint64

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "hash/maphash"
  5. )
  6. func main() {
  7. seed := maphash.MakeSeed()
  8. a := maphash.String(seed, "gopher")
  9. b := maphash.String(seed, "gopher")
  10. c := maphash.String(seed, "Gopher")
  11. fmt.Println("same seed, same input:", a == b)
  12. fmt.Println("same seed, diff input:", a == c)
  13. other := maphash.MakeSeed()
  14. fmt.Println("diff seed, same input:", a == maphash.String(other, "gopher"))
  15. }

輸出:
  1. same seed, same input: true
  2. same seed, diff input: false
  3. diff seed, same input: false

Bytes


Bytes 和 String 一樣,只是輸入是位元組切片。同一個種子下,內容相同的字串與位元組切片會得到相同的值。
簽名:
  1. func Bytes(seed Seed, b []byte) uint64

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "hash/maphash"
  5. )
  6. func main() {
  7. seed := maphash.MakeSeed()
  8. fromBytes := maphash.Bytes(seed, []byte("gopher"))
  9. fromString := maphash.String(seed, "gopher")
  10. fmt.Println("Bytes == String:", fromBytes == fromString)
  11. fmt.Println("empty input ok:", maphash.Bytes(seed, nil) == maphash.String(seed, ""))
  12. }

輸出:
  1. Bytes == String: true
  2. empty input ok: true

Comparable


Go 1.24 起新增泛型函式 Comparable,可以直接雜湊任何可比較(comparable)的值:整數、結構體、陣列、指標都行,不必先自己轉成位元組。規則是:v1 == v2 就保證雜湊值相同。泛型觀念見 泛型函式。
注意:浮點數 NaN 不等於自己,所以它的雜湊值是隨機的。
簽名:
  1. func Comparable[T comparable](seed Seed, v T) uint64

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "hash/maphash"
  5. "math"
  6. )
  7. type Point struct {
  8. X, Y int
  9. }
  10. func main() {
  11. seed := maphash.MakeSeed()
  12. p1 := maphash.Comparable(seed, Point{1, 2})
  13. p2 := maphash.Comparable(seed, Point{1, 2})
  14. p3 := maphash.Comparable(seed, Point{2, 1})
  15. fmt.Println("Point{1,2} twice:", p1 == p2)
  16. fmt.Println("Point{1,2} vs {2,1}:", p1 == p3)
  17. fmt.Println("[3]int equal:", maphash.Comparable(seed, [3]int{1, 2, 3}) == maphash.Comparable(seed, [3]int{1, 2, 3}))
  18. fmt.Println("NaN twice:", maphash.Comparable(seed, math.NaN()) == maphash.Comparable(seed, math.NaN()))
  19. }

輸出:
  1. Point{1,2} twice: true
  2. Point{1,2} vs {2,1}: false
  3. [3]int equal: true
  4. NaN twice: false

Hash 串流雜湊


maphash.Hash 是可以分段寫入的雜湊器,實作了 hash 套件的 hash.Hash64。它的零值就能用,第一次使用時會自動挑一個隨機種子;Sum64() 取得結果。
不管用 Write、WriteString 或 WriteByte,只要餵進去的位元組序列相同,結果就相同。
簽名:
  1. func (h *Hash) Write(b []byte) (int, error)
  2. func (h *Hash) WriteString(s string) (int, error)
  3. func (h *Hash) WriteByte(b byte) error
  4. func (h *Hash) Sum64() uint64
  5. func (h *Hash) Reset()

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "hash/maphash"
  5. )
  6. func main() {
  7. var h maphash.Hash
  8. h.WriteString("foo")
  9. whole := h.Sum64()
  10. h.Reset()
  11. h.WriteByte('f')
  12. h.Write([]byte("o"))
  13. h.WriteString("o")
  14. parts := h.Sum64()
  15. fmt.Println("same bytes, same hash:", whole == parts)
  16. fmt.Println("equals String():", whole == maphash.String(h.Seed(), "foo"))
  17. fmt.Println("Size:", h.Size())
  18. }

輸出:
  1. same bytes, same hash: true
  2. equals String(): true
  3. Size: 8

SetSeed 共用種子


Hash 不能被多個 goroutine 同時使用,但 Seed 可以。多個 goroutine 要算出一致的雜湊值時,每個 goroutine 各自宣告一個 Hash,再用 SetSeed 設成同一個種子。Seed() 則取回目前使用的種子。
併發觀念見 Goroutine 與 WaitGroup 與 Once。
簽名:
  1. func (h *Hash) SetSeed(seed Seed)
  2. func (h *Hash) Seed() Seed

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "hash/maphash"
  5. "sync"
  6. )
  7. func main() {
  8. seed := maphash.MakeSeed()
  9. results := make([]uint64, 4)
  10. var wg sync.WaitGroup
  11. for i := range results {
  12. wg.Go(func() {
  13. var h maphash.Hash
  14. h.SetSeed(seed)
  15. h.WriteString("shared-key")
  16. results[i] = h.Sum64()
  17. })
  18. }
  19. wg.Wait()
  20. allSame := true
  21. for _, r := range results {
  22. if r != results[0] {
  23. allSame = false
  24. }
  25. }
  26. fmt.Println("all goroutines agree:", allSame)
  27. fmt.Println("matches String():", results[0] == maphash.String(seed, "shared-key"))
  28. }

輸出:
  1. all goroutines agree: true
  2. matches String(): true

WriteComparable


Go 1.24 起新增 WriteComparable,把一個可比較的值寫進 Hash。適合組合多個欄位算一個雜湊,例如「使用者 ID + 日期」當複合鍵。
簽名:
  1. func WriteComparable[T comparable](h *Hash, x T)

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "hash/maphash"
  5. )
  6. type Key struct {
  7. UserID int
  8. Day string
  9. }
  10. func hashKey(seed maphash.Seed, k Key) uint64 {
  11. var h maphash.Hash
  12. h.SetSeed(seed)
  13. maphash.WriteComparable(&h, k.UserID)
  14. maphash.WriteComparable(&h, k.Day)
  15. return h.Sum64()
  16. }
  17. func main() {
  18. seed := maphash.MakeSeed()
  19. a := hashKey(seed, Key{42, "2024-01-01"})
  20. b := hashKey(seed, Key{42, "2024-01-01"})
  21. c := hashKey(seed, Key{42, "2024-01-02"})
  22. fmt.Println("same key:", a == b)
  23. fmt.Println("diff day:", a == c)
  24. }

輸出:
  1. same key: true
  2. diff day: false

實戰:用雜湊值挑分片


雜湊值最常見的用法是取餘數決定「放進哪一格」。下面做一個分成 8 個分片、每片各有一把 互斥鎖 的計數器:同一個鍵永遠落在同一個分片,不同鍵分散開來,鎖的競爭就變少了。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "hash/maphash"
  5. "sync"
  6. )
  7. const SHARDS = 8
  8. type shard struct {
  9. mu sync.Mutex
  10. counts map[string]int
  11. }
  12. type Counter struct {
  13. seed maphash.Seed
  14. shards [SHARDS]*shard
  15. }
  16. func NewCounter() *Counter {
  17. c := &Counter{seed: maphash.MakeSeed()}
  18. for i := range c.shards {
  19. c.shards[i] = &shard{counts: map[string]int{}}
  20. }
  21. return c
  22. }
  23. func (c *Counter) index(key string) uint64 {
  24. return maphash.String(c.seed, key) % SHARDS
  25. }
  26. func (c *Counter) Inc(key string) {
  27. s := c.shards[c.index(key)]
  28. s.mu.Lock()
  29. s.counts[key]++
  30. s.mu.Unlock()
  31. }
  32. func (c *Counter) Get(key string) int {
  33. s := c.shards[c.index(key)]
  34. s.mu.Lock()
  35. defer s.mu.Unlock()
  36. return s.counts[key]
  37. }
  38. func main() {
  39. c := NewCounter()
  40. var wg sync.WaitGroup
  41. for range 100 {
  42. wg.Go(func() {
  43. c.Inc("apple")
  44. c.Inc("banana")
  45. })
  46. }
  47. wg.Wait()
  48. fmt.Println("apple:", c.Get("apple"))
  49. fmt.Println("banana:", c.Get("banana"))
  50. fmt.Println("stable shard:", c.index("apple") == c.index("apple"))
  51. }

輸出:
  1. apple: 100
  2. banana: 100
  3. stable shard: true

重點整理


  • maphash 給雜湊表、分片等自訂資料結構用,速度快、分布均勻
  • 雜湊值取決於種子,種子每次啟動都不同,所以結果不能存檔或跨程序比對
  • Seed 零值無效,一律用 MakeSeed();Seed 可跨 goroutine 共用,Hash 不行
  • 一次性計算用 String/Bytes/Comparable;分段寫入用 Hash
  • Go 1.24 起 Comparable、WriteComparable 可直接雜湊結構體等可比較值
  • 不是加密雜湊,防竄改請用 crypto/sha256

資料來源