How to Copy a Map in Golang

To copy a Map in Golang, you must “create a new map and copy each key-value pair from the original map to the new one”. This is because go maps are “reference types, ” meaning when you assign a map to another variable, both variables refer to the same underlying map data.

Example

package main

import (
  "fmt"
)

func main() {
  originalMap := map[string]int{
    "A": 21,
    "B": 19,
    "C": 18,
  }

  copiedMap := copyMap(originalMap)

  // Modify the original map
  originalMap["D"] = 4

  // Print both maps to show that they are independent
  fmt.Println("Original map:", originalMap)
  fmt.Println("Copied map:", copiedMap)
}

func copyMap(src map[string]int) map[string]int {
  dst := make(map[string]int, len(src))
  for k, v := range src {
    dst[k] = v
  }
  return dst
}

Output

Original map: map[A:21 B:19 C:18 D:4]

Copied map: map[A:21 B:19 C:18]

In this code, the “copyMap()” function takes a source map (src) as input and creates a new destination map (dst) with the same length as the source map.

In the next step, it iterates through each key-value pair in the source map and inserts it into the destination map.

The function returns the destination map as a result.

The main() function demonstrates the use of the “copyMap()” function by creating an originalMap, copying it to copiedMap, and then modifying the originalMap.

You can see that after copying the map, we modified the originalMap by adding a new property, “D” and after modifying it, it does not affect the copiedMap, which means both are independent.

Leave a Comment