diff --git a/maputil/map.go b/maputil/map.go index 87b3a8b..d0d9d58 100644 --- a/maputil/map.go +++ b/maputil/map.go @@ -70,7 +70,12 @@ func ValuesBy[K comparable, V any, T any](m map[K]V, mapper func(item V) T) []T // Merge maps, next key will overwrite previous key. // Play: https://go.dev/play/p/H95LENF1uB- func Merge[K comparable, V any](maps ...map[K]V) map[K]V { - result := make(map[K]V, 0) + size := 0 + for i := range maps { + size += len(maps[i]) + } + + result := make(map[K]V, size) for _, m := range maps { for k, v := range m { diff --git a/maputil/map_test.go b/maputil/map_test.go index 30c7ae6..94b8a92 100644 --- a/maputil/map_test.go +++ b/maputil/map_test.go @@ -107,14 +107,14 @@ func TestMerge(t *testing.T) { 2: "b", } m2 := map[int]string{ - 1: "1", - 3: "2", + 2: "c", + 3: "d", } expected := map[int]string{ - 1: "1", - 2: "b", - 3: "2", + 1: "a", + 2: "c", + 3: "d", } acturl := Merge(m1, m2)