Getting the union of two maps in go

jeffknupp picture jeffknupp · Mar 24, 2014 · Viewed 64.1k times · Source

I have a recursive function that creates objects representing file paths (the keys are paths and the values are info about the file). It's recursive as it's only meant to handle files, so if a directory is encountered, the function is recursively called on the directory.

All that being said, I'd like to do the equivalent of a set union on two maps (i.e. the "main" map updated with the values from the recursive call). Is there an idiomatic way to do this aside from iterating over one map and assigning each key, value in it to the same thing in the other map?

That is: given a,b are of type map [string] *SomeObject, and a and b are eventually populated, is there any way to update a with all the values in b?

Answer

ANisus picture ANisus · Mar 24, 2014

There is no built in way, nor any method in the standard packages to do such a merge.

The idomatic way is to simply iterate:

for k, v := range b {
    a[k] = v
}