0
0
GoHow-ToBeginner · 3 min read

How to Merge Two Maps in Go: Simple Guide and Example

In Go, you merge two maps by iterating over one map and assigning its keys and values to the other map using for range loop. This copies all entries from the source map into the destination map, overwriting keys if they exist.
📐

Syntax

To merge two maps in Go, use a for range loop to copy each key-value pair from the source map to the destination map.

  • destMap[key] = value: assigns or overwrites the key in the destination map.
  • for key, value := range sourceMap: loops over all entries in the source map.
go
for key, value := range sourceMap {
    destMap[key] = value
}
💻

Example

This example shows how to merge two maps of string keys and int values. The second map's entries overwrite any duplicate keys in the first map.

go
package main

import "fmt"

func main() {
    map1 := map[string]int{"apple": 5, "banana": 3}
    map2 := map[string]int{"banana": 7, "cherry": 10}

    // Merge map2 into map1
    for key, value := range map2 {
        map1[key] = value
    }

    fmt.Println("Merged map:", map1)
}
Output
Merged map: map[apple:5 banana:7 cherry:10]
⚠️

Common Pitfalls

One common mistake is trying to merge maps without initializing the destination map, which causes a runtime panic. Also, remember that map keys are unique, so merging will overwrite existing keys.

Wrong way (uninitialized map):

go
package main

func main() {
    var map1 map[string]int // map1 is nil
    map2 := map[string]int{"key": 1}

    // This will panic: assignment to entry in nil map
    for k, v := range map2 {
        map1[k] = v
    }
}
📊

Quick Reference

  • Always initialize the destination map before merging.
  • Use for range to copy entries.
  • Keys in the source map overwrite keys in the destination map if duplicated.

Key Takeaways

Use a for range loop to copy key-value pairs from one map to another in Go.
Always initialize the destination map before merging to avoid runtime errors.
Merging overwrites duplicate keys in the destination map with values from the source map.
Maps in Go do not have a built-in merge function, so manual copying is required.
Check for nil maps before merging to prevent panics.