How to Merge Two Maps in Go

Merge two Go maps using maps.Copy in Go 1.21+ or a manual loop for earlier versions.

Use the maps.Copy function to merge two maps in Go 1.21 and later.

import "maps"

m1 := map[string]int{"a": 1}
m2 := map[string]int{"b": 2}

maps.Copy(m1, m2)
// m1 is now {"a": 1, "b": 2}

For Go versions prior to 1.21, iterate over the source map and assign values to the destination map manually.

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