What is the intended use-case for this? Depending on the purpose, you might 
have a look at mergo, https://github.com/imdario/mergo as it does something 
similar, mostly for pulling configuration settings from multiple places and 
combining them with defaults.

For JSON maps, there is https://github.com/peterbourgon/mergemap , and for 
simpler situations (i.e. merging JSON structs without merging embedded 
slices or maps), this solution https://play.golang.org/p/8jlJUbEJKf from 
rog in this 
post https://groups.google.com/forum/#!topic/golang-nuts/nLCy75zMlS8.

As to the code itself, let's see...

I do find it a little odd that when asked to merge A, and B, passed in that 
order, it returns B, A when both items are ints or strings, but if A is a 
slice, then B is appended to A's slice.

So mergeDataStructures("A", "B") = ["B", "A"], while 
mergeDataStructures([]interface{}{"A"},"B") = ["A", "B"]

Just looks like an accidental flipping of b and a to me, easily fixed.

Meanwhile mergeDataStructures("A",[]interface{}{"B"}) panics. (i.e. case 
string: case []interface{}), and even if that code did work, it only 
references a, so it would be returning an incomplete result even if it did 
work.

When handed two similar items on the same level - two strings or two ints 
or an int and a string, it promotes the return object to a slice, whereas 
when the same key with different values appears in two maps being merged, 
one overwrites the other instead of being promoted. It can't handle structs 
apparently at all (just a suggestion: many structs can be JSON marshaled 
and unmarshaled to an map[string]interface{}, which might let them be 
incorporated fairly simply).

Moving on to the question of elegance:

To my knowledge, there is no simpler way in Go to merge two maps other than 
to iterate over one, settings the keys and values into the other 
(obviously, the one being iterated over effectively has precedence, 
overwriting the corresponding values in the other). As to merging slices as 
you have done, well, that rather depends on the intended semantics, so I'm 
not sure you can do it generically without being wrong for at least some 
cases. After all, a slice in an arbitrary data structure or document might 
be sorted or unsorted, or it might be being used as a set and so need to 
reject duplicate items.

So while it might need a few cases tweaked, I think in general you have a 
reasonably workable solution. I do see that this code does not handle 
hierarchical maps - it assigns all of a's map values to a map, then all of 
b's to the same map, without regard for whether they are duplicated.

Howard

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to