Nafeem Haque

Software Engineer

16 Feb 2023

Merging Two Maps In Golang

Map is a built in data structure provided by golang. It is used to store key,value pairs. You can use maps for different purposes and therefore it is important to know features and tricks to deal with maps. Today we will take a look at how we can merge two different maps into one.

There could be multiple ways to merge maps including using third party libraries. but lets look at two ways we can achieve this by using just the language itself.

Using a third map to store the result of merging maps

package main

import "fmt"

func main() {
	map1 := map[string]string{
		"key1": "value1",
	}

	map2 := map[string]string{
		"key2": "value2",
	}

	map3 := make(map[string]string)

	for k, v := range map1 {
		map3[k] = v
	}

	for k, v := range map2 {
		map3[k] = v
	}

	fmt.Println(map1)
	fmt.Println(map2)
	fmt.Println(map3)
}

this provides the following output:

map[key1:value1]
map[key2:value2]
map[key1:value1 key2:value2]

This is a solution, but is it a good way to do it ?

Loop over one map and merge from the second map

package main

import "fmt"

func main() {
	src := map[string]string{
		"key1": "value1",
	}

	dst := map[string]string{
		"key2": "value2",
	}

	for k, v := range src {
		dst[k] = v
	}

	fmt.Println(src)
	fmt.Println(dst)

}

provides the following output :

map[key1:value1]
map[key1:value1 key2:value2]

for this solution we did not need another map, but our dst map is modified.

great,so we have learnt how to merge two maps, but what if two of the maps have same key with different values ?

Well, it is up to the user whether they want to update or ignore updating. If decided to ignore we can do the following to the loop.

for k, v := range src {
	_, has := dst[k]
	if has {
		continue
	}

	dst[k] = v
}

fmt.Println(src)
fmt.Println(dst)

this would result in the following :

map[key1:value1 key2:value3]
map[key1:value1 key2:value2]