Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the union of two maps in go

Tags:

union

go

map

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?

like image 779
jeffknupp Avatar asked Mar 24 '14 22:03

jeffknupp


People also ask

How to check 2 maps are equal in Golang?

In Go language, you are allowed to compare two maps with each other using DeepEqual() function provided by the reflect package. This function returns true if both the maps satisfy the following conditions: Both maps are nil or non-nil. Both maps have the same length.

How do I merge maps in Golang?

To do the merge, simply range over the maps to be merged, and append each value from the source maps to the slice associated with the same key in the result map. One thing to look out for is that once you do the append, you have to assign back the result slice to the same key in the result map.

How do I copy a map in Golang?

Maps in Go are reference types, so to deep copy the contents of a map, you cannot assign one instance to another. You can do this by creating a new, empty map and then iterating over the old map in a for range loop to assign the appropriate key-value pairs to the new map.


1 Answers

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 } 
like image 140
ANisus Avatar answered Oct 05 '22 06:10

ANisus