maps.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. // Keys returns the keys of the map m.
  7. // The keys will be in an indeterminate order.
  8. func Keys[M ~map[K]V, K comparable, V any](m M) []K {
  9. r := make([]K, 0, len(m))
  10. for k := range m {
  11. r = append(r, k)
  12. }
  13. return r
  14. }
  15. // Values returns the values of the map m.
  16. // The values will be in an indeterminate order.
  17. func Values[M ~map[K]V, K comparable, V any](m M) []V {
  18. r := make([]V, 0, len(m))
  19. for _, v := range m {
  20. r = append(r, v)
  21. }
  22. return r
  23. }
  24. // Equal reports whether two maps contain the same key/value pairs.
  25. // Values are compared using ==.
  26. func Equal[M1, M2 ~map[K]V, K, V comparable](m1 M1, m2 M2) bool {
  27. if len(m1) != len(m2) {
  28. return false
  29. }
  30. for k, v1 := range m1 {
  31. if v2, ok := m2[k]; !ok || v1 != v2 {
  32. return false
  33. }
  34. }
  35. return true
  36. }
  37. // EqualFunc is like Equal, but compares values using eq.
  38. // Keys are still compared with ==.
  39. 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 {
  40. if len(m1) != len(m2) {
  41. return false
  42. }
  43. for k, v1 := range m1 {
  44. if v2, ok := m2[k]; !ok || !eq(v1, v2) {
  45. return false
  46. }
  47. }
  48. return true
  49. }
  50. // Clear removes all entries from m, leaving it empty.
  51. func Clear[M ~map[K]V, K comparable, V any](m M) {
  52. for k := range m {
  53. delete(m, k)
  54. }
  55. }
  56. // Clone returns a copy of m. This is a shallow clone:
  57. // the new keys and values are set using ordinary assignment.
  58. func Clone[M ~map[K]V, K comparable, V any](m M) M {
  59. // Preserve nil in case it matters.
  60. if m == nil {
  61. return nil
  62. }
  63. r := make(M, len(m))
  64. for k, v := range m {
  65. r[k] = v
  66. }
  67. return r
  68. }
  69. // Copy copies all key/value pairs in src adding them to dst.
  70. // When a key in src is already present in dst,
  71. // the value in dst will be overwritten by the value associated
  72. // with the key in src.
  73. func Copy[M1 ~map[K]V, M2 ~map[K]V, K comparable, V any](dst M1, src M2) {
  74. for k, v := range src {
  75. dst[k] = v
  76. }
  77. }
  78. // DeleteFunc deletes any key/value pairs from m for which del returns true.
  79. func DeleteFunc[M ~map[K]V, K comparable, V any](m M, del func(K, V) bool) {
  80. for k, v := range m {
  81. if del(k, v) {
  82. delete(m, k)
  83. }
  84. }
  85. }