How to Merge Maps in Golang

A map in Go is a collection that stores key-value pairs in an unsorted fashion. Maps are a flexible and economical alternative to other data structures like slices and arrays.

How to merge maps in Golang

To merge the maps in Golang, you can use the for loop to traverse over one map and append its key-value pairs to the second map.

To either replace or keep the second map’s values, you can use this approach.

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]

In this example, we created two maps with four different key: value pairs. 

Used the Prinln() function to print the maps.

Using for loop and range, we are traversing map1 and appending map1’s key: value pair to map2 and return the merged maps.

The approach will overwrite any key-value pairs in map2 that have the same keys as those in map1. If you want to preserve the values in map2, you can check for the presence of a key in the map before adding it.

To append a new key-value pair to a map, use the syntax map[key] = value.

You must be careful while using the approach because If a key already has a value, that value will be obliterated.

That’s it for this article.

Leave a Comment