Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging maps in Go

Tags:

go

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
}
like image 679
code_martial Avatar asked Aug 29 '12 06:08

code_martial


2 Answers

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.

like image 79
Denys Séguret Avatar answered Sep 17 '22 13:09

Denys Séguret


AFAIK, there's no built-in nor library function for that. And I think your code is as good as it can get.

like image 36
zzzz Avatar answered Sep 18 '22 13:09

zzzz