find the union of two maps in go

To find the union of two maps in Go, we need to iterate over both maps and add their entries to a new map. If the same key exists in both maps, we should add the value from the second map to the new map. Here's an example implementation:

main.go
func mapUnion(m1, m2 map[string]int) map[string]int {
    result := make(map[string]int)

    for k, v := range m1 {
        result[k] = v
    }

    for k, v := range m2 {
        if val, ok := result[k]; ok {
            result[k] = val + v
        } else {
            result[k] = v
        }
    }

    return result
}
323 chars
18 lines

This function takes two maps of strings to integers as arguments and returns a new map that contains the union of their entries. We use the make function to create a new empty map called result to store the union.

We then iterate over the entries in the first map m1 and add them to result. Next, we iterate over the entries in the second map m2 and check if the key already exists in result. If it does, we add the value from m2 to the existing value in result. If it doesn't, we simply add the entry from m2 to result.

Finally, we return result, which now contains the union of both maps.

related categories

gistlibby LogSnag