What's the best way to merge key-value pairs from one map into another in Go? I'm using a simple loop, but I was wondering if there's something like PHP's array_merge
that could be used.
bigmap := map[string]string{"a":"a", "b":"b", "c":"c"}
smallmap := map[string]string{"d":"d"}
for k, v := range smallmap {
bigmap[k] = v
}
No, there isn't.
This wouldn't be so useful as the clear code you wrote is short enough and has the advantage of not hiding the implementation.
You can do your own function if you need it :
func addmap(a map[string]string, b map[string]string) {
for k,v := range b {
a[k] = v
}
}
addmap(bigmap, smallmap)
But as Go has no generics, you would have to make a different function for each concrete map type you want to use.
AFAIK, there's no built-in nor library function for that. And I think your code is as good as it can get.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With