hash/maphash
最後更新
hash/maphash 提供帶隨機種子的快速雜湊函式,專門用來實作雜湊表、分片(sharding)、布隆過濾器這類自訂資料結構。這個套件做什麼
Go 內建的 映射 背後就是雜湊表,但 runtime 用的雜湊函式沒有公開。當你要自己做資料結構,例如「把鍵平均分到 16 個分片,每片各有一把鎖」,就需要一個又快、分布又均勻的雜湊函式,
maphash 就是把 runtime 那一套開放出來。它和其他雜湊套件的差別在於種子(seed):
- 每個
Seed都是隨機產生的,同一個種子對同一個輸入永遠得到同樣的值 - 換一個種子,結果就完全不同;每次程式重新啟動,
MakeSeed給的種子也不同 - 種子不能序列化,也不能在另一個程序重建
所以 maphash 的值只能在同一個程序內使用,不能存到檔案或資料庫、不能跨機器比對。需要穩定、可重現的雜湊值請用
hash/fnv 或 hash/crc32;需要防竄改請用 crypto/sha256。隨機種子的好處是攻擊者猜不到雜湊值,難以刻意製造大量碰撞把雜湊表拖慢。
本頁的範例因為種子每次不同,只印比較結果(true/false),不印雜湊值本身。
匯入
- import "hash/maphash"
常用 API
MakeSeed 與 String
MakeSeed() 產生一個新的隨機種子。String(seed, s) 用這個種子算出字串的 64 位元雜湊值。注意:
Seed 的零值是無效的,一定要用 MakeSeed 建立。簽名:
- func MakeSeed() Seed
- func String(seed Seed, s string) uint64
範例:
- package main
- import (
- "fmt"
- "hash/maphash"
- )
- func main() {
- seed := maphash.MakeSeed()
- a := maphash.String(seed, "gopher")
- b := maphash.String(seed, "gopher")
- c := maphash.String(seed, "Gopher")
- fmt.Println("same seed, same input:", a == b)
- fmt.Println("same seed, diff input:", a == c)
- other := maphash.MakeSeed()
- fmt.Println("diff seed, same input:", a == maphash.String(other, "gopher"))
- }
輸出:
- same seed, same input: true
- same seed, diff input: false
- diff seed, same input: false
Bytes
Bytes 和 String 一樣,只是輸入是位元組切片。同一個種子下,內容相同的字串與位元組切片會得到相同的值。簽名:
- func Bytes(seed Seed, b []byte) uint64
範例:
- package main
- import (
- "fmt"
- "hash/maphash"
- )
- func main() {
- seed := maphash.MakeSeed()
- fromBytes := maphash.Bytes(seed, []byte("gopher"))
- fromString := maphash.String(seed, "gopher")
- fmt.Println("Bytes == String:", fromBytes == fromString)
- fmt.Println("empty input ok:", maphash.Bytes(seed, nil) == maphash.String(seed, ""))
- }
輸出:
- Bytes == String: true
- empty input ok: true
Comparable
Go 1.24 起新增泛型函式
Comparable,可以直接雜湊任何可比較(comparable)的值:整數、結構體、陣列、指標都行,不必先自己轉成位元組。規則是:v1 == v2 就保證雜湊值相同。泛型觀念見 泛型函式。注意:浮點數 NaN 不等於自己,所以它的雜湊值是隨機的。
簽名:
- func Comparable[T comparable](seed Seed, v T) uint64
範例:
- package main
- import (
- "fmt"
- "hash/maphash"
- "math"
- )
- type Point struct {
- X, Y int
- }
- func main() {
- seed := maphash.MakeSeed()
- p1 := maphash.Comparable(seed, Point{1, 2})
- p2 := maphash.Comparable(seed, Point{1, 2})
- p3 := maphash.Comparable(seed, Point{2, 1})
- fmt.Println("Point{1,2} twice:", p1 == p2)
- fmt.Println("Point{1,2} vs {2,1}:", p1 == p3)
- fmt.Println("[3]int equal:", maphash.Comparable(seed, [3]int{1, 2, 3}) == maphash.Comparable(seed, [3]int{1, 2, 3}))
- fmt.Println("NaN twice:", maphash.Comparable(seed, math.NaN()) == maphash.Comparable(seed, math.NaN()))
- }
輸出:
- Point{1,2} twice: true
- Point{1,2} vs {2,1}: false
- [3]int equal: true
- NaN twice: false
Hash 串流雜湊
maphash.Hash 是可以分段寫入的雜湊器,實作了 hash 套件的 hash.Hash64。它的零值就能用,第一次使用時會自動挑一個隨機種子;Sum64() 取得結果。不管用
Write、WriteString 或 WriteByte,只要餵進去的位元組序列相同,結果就相同。簽名:
- func (h *Hash) Write(b []byte) (int, error)
- func (h *Hash) WriteString(s string) (int, error)
- func (h *Hash) WriteByte(b byte) error
- func (h *Hash) Sum64() uint64
- func (h *Hash) Reset()
範例:
- package main
- import (
- "fmt"
- "hash/maphash"
- )
- func main() {
- var h maphash.Hash
- h.WriteString("foo")
- whole := h.Sum64()
- h.Reset()
- h.WriteByte('f')
- h.Write([]byte("o"))
- h.WriteString("o")
- parts := h.Sum64()
- fmt.Println("same bytes, same hash:", whole == parts)
- fmt.Println("equals String():", whole == maphash.String(h.Seed(), "foo"))
- fmt.Println("Size:", h.Size())
- }
輸出:
- same bytes, same hash: true
- equals String(): true
- Size: 8
SetSeed 共用種子
Hash 不能被多個 goroutine 同時使用,但 Seed 可以。多個 goroutine 要算出一致的雜湊值時,每個 goroutine 各自宣告一個 Hash,再用 SetSeed 設成同一個種子。Seed() 則取回目前使用的種子。併發觀念見 Goroutine 與 WaitGroup 與 Once。
簽名:
- func (h *Hash) SetSeed(seed Seed)
- func (h *Hash) Seed() Seed
範例:
- package main
- import (
- "fmt"
- "hash/maphash"
- "sync"
- )
- func main() {
- seed := maphash.MakeSeed()
- results := make([]uint64, 4)
- var wg sync.WaitGroup
- for i := range results {
- wg.Go(func() {
- var h maphash.Hash
- h.SetSeed(seed)
- h.WriteString("shared-key")
- results[i] = h.Sum64()
- })
- }
- wg.Wait()
- allSame := true
- for _, r := range results {
- if r != results[0] {
- allSame = false
- }
- }
- fmt.Println("all goroutines agree:", allSame)
- fmt.Println("matches String():", results[0] == maphash.String(seed, "shared-key"))
- }
輸出:
- all goroutines agree: true
- matches String(): true
WriteComparable
Go 1.24 起新增
WriteComparable,把一個可比較的值寫進 Hash。適合組合多個欄位算一個雜湊,例如「使用者 ID + 日期」當複合鍵。簽名:
- func WriteComparable[T comparable](h *Hash, x T)
範例:
- package main
- import (
- "fmt"
- "hash/maphash"
- )
- type Key struct {
- UserID int
- Day string
- }
- func hashKey(seed maphash.Seed, k Key) uint64 {
- var h maphash.Hash
- h.SetSeed(seed)
- maphash.WriteComparable(&h, k.UserID)
- maphash.WriteComparable(&h, k.Day)
- return h.Sum64()
- }
- func main() {
- seed := maphash.MakeSeed()
- a := hashKey(seed, Key{42, "2024-01-01"})
- b := hashKey(seed, Key{42, "2024-01-01"})
- c := hashKey(seed, Key{42, "2024-01-02"})
- fmt.Println("same key:", a == b)
- fmt.Println("diff day:", a == c)
- }
輸出:
- same key: true
- diff day: false
實戰:用雜湊值挑分片
雜湊值最常見的用法是取餘數決定「放進哪一格」。下面做一個分成 8 個分片、每片各有一把 互斥鎖 的計數器:同一個鍵永遠落在同一個分片,不同鍵分散開來,鎖的競爭就變少了。
範例:
- package main
- import (
- "fmt"
- "hash/maphash"
- "sync"
- )
- const SHARDS = 8
- type shard struct {
- mu sync.Mutex
- counts map[string]int
- }
- type Counter struct {
- seed maphash.Seed
- shards [SHARDS]*shard
- }
- func NewCounter() *Counter {
- c := &Counter{seed: maphash.MakeSeed()}
- for i := range c.shards {
- c.shards[i] = &shard{counts: map[string]int{}}
- }
- return c
- }
- func (c *Counter) index(key string) uint64 {
- return maphash.String(c.seed, key) % SHARDS
- }
- func (c *Counter) Inc(key string) {
- s := c.shards[c.index(key)]
- s.mu.Lock()
- s.counts[key]++
- s.mu.Unlock()
- }
- func (c *Counter) Get(key string) int {
- s := c.shards[c.index(key)]
- s.mu.Lock()
- defer s.mu.Unlock()
- return s.counts[key]
- }
- func main() {
- c := NewCounter()
- var wg sync.WaitGroup
- for range 100 {
- wg.Go(func() {
- c.Inc("apple")
- c.Inc("banana")
- })
- }
- wg.Wait()
- fmt.Println("apple:", c.Get("apple"))
- fmt.Println("banana:", c.Get("banana"))
- fmt.Println("stable shard:", c.index("apple") == c.index("apple"))
- }
輸出:
- apple: 100
- banana: 100
- stable shard: true
重點整理
- maphash 給雜湊表、分片等自訂資料結構用,速度快、分布均勻
- 雜湊值取決於種子,種子每次啟動都不同,所以結果不能存檔或跨程序比對
Seed零值無效,一律用MakeSeed();Seed可跨 goroutine 共用,Hash不行- 一次性計算用
String/Bytes/Comparable;分段寫入用Hash - Go 1.24 起
Comparable、WriteComparable可直接雜湊結構體等可比較值 - 不是加密雜湊,防竄改請用
crypto/sha256