# maps

`maps` 提供適用於任何映射型別的泛型函式：複製、比較、條件刪除，以及和迭代器互相轉換，Go 1.21 起。

## 這個套件做什麼

映射（map）是「鍵對應值」的資料結構，觀念見 [映射](/composite-maps)。日常的新增、查詢、刪除用語法本身（`m[k] = v`、`v, ok := m[k]`、`delete(m, k)`）就夠了；`maps` 套件補上語法沒有直接提供的整批操作：

- 複製一份映射，讓修改不互相影響
- 判斷兩個映射內容是否相同（映射不能用 `==` 比較）
- 依條件刪除多個鍵
- 取得所有鍵或值，再排序、轉切片（Go 1.23 起，透過迭代器）

注意：映射的走訪順序是隨機的。需要固定順序輸出時，先用 `slices.Sorted(maps.Keys(m))` 取得排序後的鍵。

和 [`slices`](/pkg-slices) 的分工：`slices` 處理切片，`maps` 處理映射，兩者常搭配使用。

## 匯入

```go
import "maps"
```

## 常用 API

### Keys 與 Values

回傳一個迭代器，依序產生映射的所有鍵或值（Go 1.23 起）。迭代器可以直接用 `for range` 走訪，或交給 `slices.Sorted`、`slices.Collect` 轉成切片。

注意：產生的順序不固定，每次執行可能不同；要穩定的結果請排序。

簽名：

```go
func Keys[Map ~map[K]V, K comparable, V any](m Map) iter.Seq[K]
func Values[Map ~map[K]V, K comparable, V any](m Map) iter.Seq[V]
```

範例：

```go
package main

import (
	"fmt"
	"maps"
	"slices"
)

func main() {
	prices := map[string]int{"coffee": 80, "tea": 50, "juice": 65}

	keys := slices.Sorted(maps.Keys(prices))
	fmt.Println(keys)

	values := slices.Sorted(maps.Values(prices))
	fmt.Println(values)

	for _, k := range keys {
		fmt.Printf("%s=%d\n", k, prices[k])
	}
}
```

輸出：

```text
[coffee juice tea]
[50 65 80]
coffee=80
juice=65
tea=50
```

### All、Collect 與 Insert

`All` 把映射轉成產生「鍵、值」成對資料的迭代器（`iter.Seq2`）；`Collect` 把這種迭代器收集成新映射；`Insert` 把迭代器的內容加進既有映射，相同的鍵會被覆蓋。三者都是 Go 1.23 起。

常見用途是串接處理：例如把切片的 `slices.All`（索引、元素）直接收集成映射。

簽名：

```go
func All[Map ~map[K]V, K comparable, V any](m Map) iter.Seq2[K, V]
func Collect[K comparable, V any](seq iter.Seq2[K, V]) map[K]V
func Insert[Map ~map[K]V, K comparable, V any](m Map, seq iter.Seq2[K, V])
```

範例：

```go
package main

import (
	"fmt"
	"maps"
	"slices"
)

func main() {
	byIndex := maps.Collect(slices.All([]string{"zero", "one", "two"}))
	fmt.Println(byIndex)

	defaults := map[string]string{"host": "localhost", "port": "80"}
	custom := map[string]string{"port": "8080", "debug": "true"}

	cfg := maps.Collect(maps.All(defaults))
	maps.Insert(cfg, maps.All(custom))
	fmt.Println(cfg)
	fmt.Println(defaults)
}
```

輸出：

```text
map[0:zero 1:one 2:two]
map[debug:true host:localhost port:8080]
map[host:localhost port:80]
```

`fmt.Println` 印映射時會依鍵排序，所以輸出順序是固定的。

### Clone

建立一份內容相同的新映射。映射是參考型別，直接指派 `b := a` 只是讓兩個變數指向同一份資料；要獨立修改就得 `Clone`。

注意：`Clone` 是淺層複製，值如果是切片、指標或另一個映射，複本裡仍指向同一份底層資料。對 nil 映射呼叫會回傳 nil。

簽名：

```go
func Clone[M ~map[K]V, K comparable, V any](m M) M
```

範例：

```go
package main

import (
	"fmt"
	"maps"
)

func main() {
	orig := map[string]int{"a": 1, "b": 2}

	alias := orig
	alias["a"] = 100
	fmt.Println(orig)

	copied := maps.Clone(orig)
	copied["b"] = 200
	fmt.Println(orig, copied)

	nested := map[string][]int{"x": {1, 2}}
	shallow := maps.Clone(nested)
	shallow["x"][0] = 999
	fmt.Println(nested)

	var nilMap map[string]int
	fmt.Println(maps.Clone(nilMap) == nil)
}
```

輸出：

```text
map[a:100 b:2]
map[a:100 b:2] map[a:100 b:200]
map[x:[999 2]]
true
```

### Copy

把 `src` 的所有鍵值複製進 `dst`，`dst` 已有的鍵會被覆蓋。和 `Insert` 的效果相同，差在參數是映射而不是迭代器。

注意：`dst` 是 nil 映射而 `src` 非空時會 panic，因為不能寫入 nil 映射。

簽名：

```go
func Copy[M1 ~map[K]V, M2 ~map[K]V, K comparable, V any](dst M1, src M2)
```

範例：

```go
package main

import (
	"fmt"
	"maps"
)

func main() {
	dst := map[string]int{"apple": 1, "pear": 2}
	src := map[string]int{"pear": 20, "fig": 30}

	maps.Copy(dst, src)
	fmt.Println(dst)
}
```

輸出：

```text
map[apple:1 fig:30 pear:20]
```

### Equal 與 EqualFunc

`Equal` 判斷兩個映射是否有相同的鍵，且每個鍵對應的值都相等。值不能用 `==` 比較（例如切片）時，改用 `EqualFunc` 自訂比較方式。

簽名：

```go
func Equal[M1, M2 ~map[K]V, K, V comparable](m1 M1, m2 M2) bool
func EqualFunc[M1 ~map[K]V1, M2 ~map[K]V2, K comparable, V1, V2 any](m1 M1, m2 M2, eq func(V1, V2) bool) bool
```

範例：

```go
package main

import (
	"fmt"
	"maps"
	"slices"
)

func main() {
	a := map[string]int{"x": 1, "y": 2}
	b := map[string]int{"y": 2, "x": 1}
	c := map[string]int{"x": 1}
	fmt.Println(maps.Equal(a, b), maps.Equal(a, c))

	g1 := map[string][]string{"team": {"ann", "bob"}}
	g2 := map[string][]string{"team": {"ann", "bob"}}
	fmt.Println(maps.EqualFunc(g1, g2, slices.Equal[[]string]))
}
```

輸出：

```text
true false
true
```

### DeleteFunc

刪除所有符合條件的鍵值對。條件函式同時收到鍵與值。比起邊走訪邊 `delete`，這個寫法更清楚。

簽名：

```go
func DeleteFunc[M ~map[K]V, K comparable, V any](m M, del func(K, V) bool)
```

範例：

```go
package main

import (
	"fmt"
	"maps"
	"strings"
)

func main() {
	sessions := map[string]int{"u1": 0, "u2": 5, "u3": 0, "tmp-1": 9}

	maps.DeleteFunc(sessions, func(id string, hits int) bool {
		return hits == 0 || strings.HasPrefix(id, "tmp-")
	})
	fmt.Println(sessions)
}
```

輸出：

```text
map[u2:5]
```

## 重點整理

- `maps` 補上映射的整批操作：`Clone`、`Copy`、`Equal`、`DeleteFunc`
- `maps.Keys`、`maps.Values`、`maps.All` 回傳迭代器（Go 1.23 起），順序不固定
- 需要固定順序時用 `slices.Sorted(maps.Keys(m))`
- `Clone` 是淺層複製；`Copy` 寫入 nil 映射會 panic
- 值不可比較時用 `EqualFunc` 自訂相等判斷

## 資料來源

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