How to Merge Maps in Golang [3 Ways]

Here are the ways to merge maps in Go:

  1. Using for loop
  2. Using generics
  3. Using copy approach

Method 1: Using for loop

Use the “for loop” to traverse over one map and append its key-value pairs to the second map.

package main

import (
  "fmt"
)

func main() {
  map1 := map[string]int{
    "bdy_kl": 10,
    "eno_kl": 21,
 }
  map2 := map[string]int{
    "bdy_kb": 20,
    "eno_kb": 19,
 }

  // Print the map before merging
  fmt.Println("The First Map: ", map1)
  fmt.Println("The Second Map: ", map2)

  for x, y := range map1 {
    map2[x] = y
  }
  fmt.Println("The merged Map is: ", map2)
}

Output

The First Map: map[bday_kl:10 eno_kl:21]
The Second Map: map[bday_kb:20 eno_kb:19]
The merged Map is: map[bday_kb:20 bday_kl:10 eno_kb:19 eno_kl:21]

Method 2: Using generics

With the introduction of generics in Go (proposed in Go 1.18), it became possible to write generic functions and data structures.

Here, I’ll show you how to merge two maps using generics.

package main

import (
  "fmt"
)

func MergeMaps[K comparable, V any](m1, m2 map[K]V) map[K]V {
  merged := make(map[K]V)

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

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

  return merged
}

func main() {
  map1 := map[int]string{
    1: "one",
    2: "two",
  }

  map2 := map[int]string{
    3: "three",
    2: "dos",
  }

  mergedMap := MergeMaps(map1, map2)
  fmt.Println(mergedMap)
}

Output

map[1:one 2:dos 3:three]

Method 3: Using Copy() Method

If you want to merge maps in Go without using generics, you can use simple for-loops to copy the contents of one map into another.

Here is the way to merge maps using the “copy method”:

package main

import (
  "fmt"
)

func MergeMaps(m1, m2 map[int]string) map[int]string {
  merged := make(map[int]string)

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

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

  return merged
}

func main() {
  map1 := map[int]string{
    1: "one",
    2: "two",
  }

  map2 := map[int]string{
    3: "three",
    2: "dos",
 }

 mergedMap := MergeMaps(map1, map2)
 fmt.Println(mergedMap)
}

Output

map[1:one 2:dos 3:three]

That’s it!