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
?
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.
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.
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.
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 }
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