combine two maps in go

If you want to combine two maps in Go, you can iterate over one of the maps and add each key-value pair to the other map. Here's an example function that takes two maps and returns the merged map:

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

    // Add all key-value pairs from m1 to result
    for k, v := range m1 {
        result[k] = v
    }

    // Add all key-value pairs from m2 to result, overwriting
    // any keys that already exist in result
    for k, v := range m2 {
        result[k] = v
    }

    return result
}
379 chars
17 lines

In this example, we use the make() function to create a new map result. Then we iterate over m1 and add each key-value pair to result using the result[k] = v syntax. Finally, we iterate over m2 and add each key-value pair to result, overwriting any keys that already exist in result.

You can then call this function with two maps and get a new map that contains all key-value pairs from both maps:

main.go
m1 := map[string]int{"a": 1, "b": 2}
m2 := map[string]int{"b": 3, "c": 4}

merged := mergeMaps(m1, m2)

fmt.Println(merged) // Output: map[a:1 b:3 c:4]
152 chars
7 lines

related categories

gistlibby LogSnag