# hash/maphash

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

## 這個套件做什麼

Go 內建的 [映射](/composite-maps) 背後就是雜湊表，但 runtime 用的雜湊函式沒有公開。當你要自己做資料結構，例如「把鍵平均分到 16 個分片，每片各有一把鎖」，就需要一個又快、分布又均勻的雜湊函式，`maphash` 就是把 runtime 那一套開放出來。

它和其他雜湊套件的差別在於**種子（seed）**：

- 每個 `Seed` 都是隨機產生的，同一個種子對同一個輸入永遠得到同樣的值
- 換一個種子，結果就完全不同；每次程式重新啟動，`MakeSeed` 給的種子也不同
- 種子不能序列化，也不能在另一個程序重建

所以 maphash 的值**只能在同一個程序內使用**，不能存到檔案或資料庫、不能跨機器比對。需要穩定、可重現的雜湊值請用 `hash/fnv` 或 [hash/crc32](/pkg-hash-crc32)；需要防竄改請用 [crypto/sha256](/pkg-crypto-sha256)。

隨機種子的好處是攻擊者猜不到雜湊值，難以刻意製造大量碰撞把雜湊表拖慢。

本頁的範例因為種子每次不同，只印比較結果（true／false），不印雜湊值本身。

## 匯入

```go
import "hash/maphash"
```

## 常用 API

### MakeSeed 與 String

`MakeSeed()` 產生一個新的隨機種子。`String(seed, s)` 用這個種子算出字串的 64 位元雜湊值。

注意：`Seed` 的零值是無效的，一定要用 `MakeSeed` 建立。

簽名：

```go
func MakeSeed() Seed
func String(seed Seed, s string) uint64
```

範例：

```go
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"))
}
```

輸出：

```text
same seed, same input: true
same seed, diff input: false
diff seed, same input: false
```

### Bytes

`Bytes` 和 `String` 一樣，只是輸入是位元組切片。同一個種子下，內容相同的字串與位元組切片會得到相同的值。

簽名：

```go
func Bytes(seed Seed, b []byte) uint64
```

範例：

```go
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, ""))
}
```

輸出：

```text
Bytes == String: true
empty input ok: true
```

### Comparable

Go 1.24 起新增泛型函式 `Comparable`，可以直接雜湊任何可比較（comparable）的值：整數、結構體、陣列、指標都行，不必先自己轉成位元組。規則是：`v1 == v2` 就保證雜湊值相同。泛型觀念見 [泛型函式](/generics-functions)。

注意：浮點數 NaN 不等於自己，所以它的雜湊值是隨機的。

簽名：

```go
func Comparable[T comparable](seed Seed, v T) uint64
```

範例：

```go
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()))
}
```

輸出：

```text
Point{1,2} twice: true
Point{1,2} vs {2,1}: false
[3]int equal: true
NaN twice: false
```

### Hash 串流雜湊

`maphash.Hash` 是可以分段寫入的雜湊器，實作了 [hash](/pkg-hash) 套件的 `hash.Hash64`。它的零值就能用，第一次使用時會自動挑一個隨機種子；`Sum64()` 取得結果。

不管用 `Write`、`WriteString` 或 `WriteByte`，只要餵進去的位元組序列相同，結果就相同。

簽名：

```go
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()
```

範例：

```go
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())
}
```

輸出：

```text
same bytes, same hash: true
equals String(): true
Size: 8
```

### SetSeed 共用種子

`Hash` 不能被多個 goroutine 同時使用，但 `Seed` 可以。多個 goroutine 要算出一致的雜湊值時，每個 goroutine 各自宣告一個 `Hash`，再用 `SetSeed` 設成同一個種子。`Seed()` 則取回目前使用的種子。

併發觀念見 [Goroutine](/concurrency-goroutines) 與 [WaitGroup 與 Once](/sync-once-waitgroup)。

簽名：

```go
func (h *Hash) SetSeed(seed Seed)
func (h *Hash) Seed() Seed
```

範例：

```go
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"))
}
```

輸出：

```text
all goroutines agree: true
matches String(): true
```

### WriteComparable

Go 1.24 起新增 `WriteComparable`，把一個可比較的值寫進 `Hash`。適合組合多個欄位算一個雜湊，例如「使用者 ID + 日期」當複合鍵。

簽名：

```go
func WriteComparable[T comparable](h *Hash, x T)
```

範例：

```go
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)
}
```

輸出：

```text
same key: true
diff day: false
```

### 實戰：用雜湊值挑分片

雜湊值最常見的用法是取餘數決定「放進哪一格」。下面做一個分成 8 個分片、每片各有一把 [互斥鎖](/sync-mutex) 的計數器：同一個鍵永遠落在同一個分片，不同鍵分散開來，鎖的競爭就變少了。

範例：

```go
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"))
}
```

輸出：

```text
apple: 100
banana: 100
stable shard: true
```

## 重點整理

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

## 資料來源

- [dsxwk/go-docs（標準庫分類架構參考）](https://github.com/dsxwk/go-docs)
- [pkg.go.dev：hash/maphash](https://pkg.go.dev/hash/maphash)
- [Go 1.26.0 原始碼：src/hash/maphash](https://github.com/golang/go/tree/go1.26.0/src/hash/maphash)
