Closed
Description
The new x/exp/maps
package covers most of the things i really wanted generics for with maps (🙏 Keys
and Values
), but the other thing i find myself doing with generic maps a lot is merging two (or more) maps into one larger map. IMO it's a common enough task to get integrated into the maps
package.
My proposed implentation is:
func Merge[M ~map[K]V, K comparable, V any](maps ...M) M {
fullCap := 0
for _, m := range maps {
fullCap += len(m)
}
merged := make(M, fullCap)
for _, m := range maps {
for key, val := range m {
merged[key] = val
}
}
return merged
}
Happy for this implementation to be changed, it's what i came up with in about 5 minutes, i'm sure it can be improved 😅
It'd be probably worth calling out in the docs, like we do for Copy
, that this is only a shallow merge and that it won't traverse deeper map map elements to try to merge them.