maps

最後更新


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

這個套件做什麼


映射(map)是「鍵對應值」的資料結構,觀念見 映射。日常的新增、查詢、刪除用語法本身(m[k] = v、v, ok := m[k]、delete(m, k))就夠了;maps 套件補上語法沒有直接提供的整批操作:
  • 複製一份映射,讓修改不互相影響
  • 判斷兩個映射內容是否相同(映射不能用 == 比較)
  • 依條件刪除多個鍵
  • 取得所有鍵或值,再排序、轉切片(Go 1.23 起,透過迭代器)

注意:映射的走訪順序是隨機的。需要固定順序輸出時,先用 slices.Sorted(maps.Keys(m)) 取得排序後的鍵。
和 slices 的分工:slices 處理切片,maps 處理映射,兩者常搭配使用。

匯入


  1. import "maps"

常用 API


Keys 與 Values


回傳一個迭代器,依序產生映射的所有鍵或值(Go 1.23 起)。迭代器可以直接用 for range 走訪,或交給 slices.Sorted、slices.Collect 轉成切片。
注意:產生的順序不固定,每次執行可能不同;要穩定的結果請排序。
簽名:
  1. func Keys[Map ~map[K]V, K comparable, V any](m Map) iter.Seq[K]
  2. func Values[Map ~map[K]V, K comparable, V any](m Map) iter.Seq[V]

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "maps"
  5. "slices"
  6. )
  7. func main() {
  8. prices := map[string]int{"coffee": 80, "tea": 50, "juice": 65}
  9. keys := slices.Sorted(maps.Keys(prices))
  10. fmt.Println(keys)
  11. values := slices.Sorted(maps.Values(prices))
  12. fmt.Println(values)
  13. for _, k := range keys {
  14. fmt.Printf("%s=%d\n", k, prices[k])
  15. }
  16. }

輸出:
  1. [coffee juice tea]
  2. [50 65 80]
  3. coffee=80
  4. juice=65
  5. tea=50

All、Collect 與 Insert


All 把映射轉成產生「鍵、值」成對資料的迭代器(iter.Seq2);Collect 把這種迭代器收集成新映射;Insert 把迭代器的內容加進既有映射,相同的鍵會被覆蓋。三者都是 Go 1.23 起。
常見用途是串接處理:例如把切片的 slices.All(索引、元素)直接收集成映射。
簽名:
  1. func All[Map ~map[K]V, K comparable, V any](m Map) iter.Seq2[K, V]
  2. func Collect[K comparable, V any](seq iter.Seq2[K, V]) map[K]V
  3. func Insert[Map ~map[K]V, K comparable, V any](m Map, seq iter.Seq2[K, V])

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "maps"
  5. "slices"
  6. )
  7. func main() {
  8. byIndex := maps.Collect(slices.All([]string{"zero", "one", "two"}))
  9. fmt.Println(byIndex)
  10. defaults := map[string]string{"host": "localhost", "port": "80"}
  11. custom := map[string]string{"port": "8080", "debug": "true"}
  12. cfg := maps.Collect(maps.All(defaults))
  13. maps.Insert(cfg, maps.All(custom))
  14. fmt.Println(cfg)
  15. fmt.Println(defaults)
  16. }

輸出:
  1. map[0:zero 1:one 2:two]
  2. map[debug:true host:localhost port:8080]
  3. map[host:localhost port:80]

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

Clone


建立一份內容相同的新映射。映射是參考型別,直接指派 b := a 只是讓兩個變數指向同一份資料;要獨立修改就得 Clone。
注意:Clone 是淺層複製,值如果是切片、指標或另一個映射,複本裡仍指向同一份底層資料。對 nil 映射呼叫會回傳 nil。
簽名:
  1. func Clone[M ~map[K]V, K comparable, V any](m M) M

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "maps"
  5. )
  6. func main() {
  7. orig := map[string]int{"a": 1, "b": 2}
  8. alias := orig
  9. alias["a"] = 100
  10. fmt.Println(orig)
  11. copied := maps.Clone(orig)
  12. copied["b"] = 200
  13. fmt.Println(orig, copied)
  14. nested := map[string][]int{"x": {1, 2}}
  15. shallow := maps.Clone(nested)
  16. shallow["x"][0] = 999
  17. fmt.Println(nested)
  18. var nilMap map[string]int
  19. fmt.Println(maps.Clone(nilMap) == nil)
  20. }

輸出:
  1. map[a:100 b:2]
  2. map[a:100 b:2] map[a:100 b:200]
  3. map[x:[999 2]]
  4. true

Copy


把 src 的所有鍵值複製進 dst,dst 已有的鍵會被覆蓋。和 Insert 的效果相同,差在參數是映射而不是迭代器。
注意:dst 是 nil 映射而 src 非空時會 panic,因為不能寫入 nil 映射。
簽名:
  1. func Copy[M1 ~map[K]V, M2 ~map[K]V, K comparable, V any](dst M1, src M2)

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "maps"
  5. )
  6. func main() {
  7. dst := map[string]int{"apple": 1, "pear": 2}
  8. src := map[string]int{"pear": 20, "fig": 30}
  9. maps.Copy(dst, src)
  10. fmt.Println(dst)
  11. }

輸出:
  1. map[apple:1 fig:30 pear:20]

Equal 與 EqualFunc


Equal 判斷兩個映射是否有相同的鍵,且每個鍵對應的值都相等。值不能用 == 比較(例如切片)時,改用 EqualFunc 自訂比較方式。
簽名:
  1. func Equal[M1, M2 ~map[K]V, K, V comparable](m1 M1, m2 M2) bool
  2. 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

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "maps"
  5. "slices"
  6. )
  7. func main() {
  8. a := map[string]int{"x": 1, "y": 2}
  9. b := map[string]int{"y": 2, "x": 1}
  10. c := map[string]int{"x": 1}
  11. fmt.Println(maps.Equal(a, b), maps.Equal(a, c))
  12. g1 := map[string][]string{"team": {"ann", "bob"}}
  13. g2 := map[string][]string{"team": {"ann", "bob"}}
  14. fmt.Println(maps.EqualFunc(g1, g2, slices.Equal[[]string]))
  15. }

輸出:
  1. true false
  2. true

DeleteFunc


刪除所有符合條件的鍵值對。條件函式同時收到鍵與值。比起邊走訪邊 delete,這個寫法更清楚。
簽名:
  1. func DeleteFunc[M ~map[K]V, K comparable, V any](m M, del func(K, V) bool)

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "maps"
  5. "strings"
  6. )
  7. func main() {
  8. sessions := map[string]int{"u1": 0, "u2": 5, "u3": 0, "tmp-1": 9}
  9. maps.DeleteFunc(sessions, func(id string, hits int) bool {
  10. return hits == 0 || strings.HasPrefix(id, "tmp-")
  11. })
  12. fmt.Println(sessions)
  13. }

輸出:
  1. 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 自訂相等判斷

資料來源