gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/maps/map.go (about) 1 package maps 2 3 type Entry[K comparable, V any] struct { 4 Key K 5 Value V 6 } 7 8 func NewEntry[K comparable, V any](k K, v V) Entry[K, V] { 9 return Entry[K, V]{Key: k, Value: v} 10 } 11 12 func Copy[K comparable, V any](m map[K]V) map[K]V { 13 n := make(map[K]V, len(m)) 14 for k, v := range m { 15 n[k] = v 16 } 17 return n 18 } 19 20 func Merge[K comparable, V any](m1, m2 map[K]V) map[K]V { 21 if m1 == nil { 22 m1 = make(map[K]V, len(m2)) 23 } 24 for k, v := range m2 { 25 m1[k] = v 26 } 27 return m1 28 } 29 30 func Keys[K comparable, V any](m map[K]V) (keys []K) { 31 keys = make([]K, 0, len(m)) 32 for k := range m { 33 keys = append(keys, k) 34 } 35 return 36 } 37 38 func Values[K comparable, V any](m map[K]V) (values []V) { 39 values = make([]V, 0, len(m)) 40 for _, v := range m { 41 values = append(values, v) 42 } 43 return 44 } 45 46 func Entries[K comparable, V any](m map[K]V) (entries []Entry[K, V]) { 47 entries = make([]Entry[K, V], 0, len(m)) 48 for k, v := range m { 49 entries = append(entries, Entry[K, V]{Key: k, Value: v}) 50 } 51 return 52 } 53 54 func Range[K comparable, V any](m map[K]V, fn func(k K, v V) bool) bool { 55 for k, v := range m { 56 if !fn(k, v) { 57 return false 58 } 59 } 60 return true 61 } 62 63 func Clear[K comparable, V any](m map[K]V) { 64 for k := range m { 65 delete(m, k) 66 } 67 }