How can I merge two maps in go?

How can I merge two maps in go?

Maps are Go's built-in associative data type (sometimes called hashes or dicts in other languages). But how do we merge two maps in Go? There is no built-in way, nor any method in the standard packages to do such a merge.

Here we will see different methods to merge a map in GoLang.

## Method 1 (The Idiomatic Way)

Here we simply iterate over the second map and add it to the first map

var asia = map[string]string{"india": "delhi", "japan":"tokyo"}

var europe = map[string]string{"germany": "berlin", "italy": "rome"}


for country, capital := range europe {

asia[country] = capital

}

//Output: map[germany:berlin india:delhi italy:rome japan:tokyo]

## Method 2 (The Copy Function)

Copy copies all key/value pairs in src adding them to dst. When a key in src is already present in dst, the value in dst will be overwritten by the value associated with the key in src. One caveat of this approach is that your maps' key type must be concrete, i.e. not an interface type. For instance, the compiler won't allow you to pass values of type map[io.Reader]int to the Copy function.

var asia = map[string]string{"india": "delhi", "japan": "tokyo"}
var europe = map[string]string{"germany": "berlin", "italy": "rome"}
maps.Copy(asia, europe)
//Output: map[germany:berlin india:delhi italy:rome japan:tokyo]

## Method 3 (The Generics)

Starting at go 1.18, thanks to the release of the Generics feature the below function will help you merge n number of maps. This! This is the way. Simple, beautiful and idiomatic.

func MergeMaps[M ~map[K]V, K comparable, V any](src ...M) M {
merged := make(M)
for _, m := range src {
    for k, v := range m {
        merged[k] = v
    }
}
return merged
}

Usage:

var asia = map[string]string{"india": "delhi", "japan": "tokyo"}

var europe = map[string]string{"germany": "berlin", "italy": "rome"}

mergedMaps := MergeMaps(asia,europe,)

So Finally, we have come to an end where we have seen how we can merge two or more maps in Golang in three different ways. Out of the above, Personally found Method 3 as my favorite because of its generic support and the way it is simple and beautiful. However, you can use any of the above methods depending on your use case.

Did you find this article valuable?

Support Vasanth Korada by becoming a sponsor. Any amount is appreciated!