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