maps.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2021 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package maps defines various functions useful with maps of any type.
  5. package maps
  6. import "maps"
  7. // TODO(adonovan): when https://go.dev/issue/32816 is accepted, all of
  8. // these functions except Keys and Values should be annotated
  9. // (provisionally with "//go:fix inline") so that tools can safely and
  10. // automatically replace calls to exp/maps with calls to std maps by
  11. // inlining them.
  12. // Keys returns the keys of the map m.
  13. // The keys will be in an indeterminate order.
  14. func Keys[M ~map[K]V, K comparable, V any](m M) []K {
  15. // The simplest true equivalent using std is:
  16. // return slices.AppendSeq(make([]K, 0, len(m)), maps.Keys(m)).
  17. r := make([]K, 0, len(m))
  18. for k := range m {
  19. r = append(r, k)
  20. }
  21. return r
  22. }
  23. // Values returns the values of the map m.
  24. // The values will be in an indeterminate order.
  25. func Values[M ~map[K]V, K comparable, V any](m M) []V {
  26. // The simplest true equivalent using std is:
  27. // return slices.AppendSeq(make([]V, 0, len(m)), maps.Values(m)).
  28. r := make([]V, 0, len(m))
  29. for _, v := range m {
  30. r = append(r, v)
  31. }
  32. return r
  33. }
  34. // Equal reports whether two maps contain the same key/value pairs.
  35. // Values are compared using ==.
  36. func Equal[M1, M2 ~map[K]V, K, V comparable](m1 M1, m2 M2) bool {
  37. return maps.Equal(m1, m2)
  38. }
  39. // EqualFunc is like Equal, but compares values using eq.
  40. // Keys are still compared with ==.
  41. 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 {
  42. return maps.EqualFunc(m1, m2, eq)
  43. }
  44. // Clear removes all entries from m, leaving it empty.
  45. func Clear[M ~map[K]V, K comparable, V any](m M) {
  46. clear(m)
  47. }
  48. // Clone returns a copy of m. This is a shallow clone:
  49. // the new keys and values are set using ordinary assignment.
  50. func Clone[M ~map[K]V, K comparable, V any](m M) M {
  51. return maps.Clone(m)
  52. }
  53. // Copy copies all key/value pairs in src adding them to dst.
  54. // When a key in src is already present in dst,
  55. // the value in dst will be overwritten by the value associated
  56. // with the key in src.
  57. func Copy[M1 ~map[K]V, M2 ~map[K]V, K comparable, V any](dst M1, src M2) {
  58. maps.Copy(dst, src)
  59. }
  60. // DeleteFunc deletes any key/value pairs from m for which del returns true.
  61. func DeleteFunc[M ~map[K]V, K comparable, V any](m M, del func(K, V) bool) {
  62. maps.DeleteFunc(m, del)
  63. }