How to copy Map in Go?

To copy a map in Go, you need to create a new map and copy the key-value pairs from the original map to the new one. Since maps in Go are reference types, simply assigning a map to another variable will create a reference to the same underlying map, not a new copy. To create an independent copy of the map, you can follow one of these approaches:

  1. Using a Loop: You can use a loop to copy the key-value pairs from the original map to a new map.
package main

import "fmt"

func main() {
    original := map[string]int{"a": 1, "b": 2, "c": 3}

    // Create a new map and copy key-value pairs.
    copied := make(map[string]int)
    for k, v := range original {
        copied[k] = v
    }

    // Modify the copied map.
    copied["a"] = 100

    // Output the original and copied maps.
    fmt.Println("Original:", original)
    fmt.Println("Copied:", copied)
}

Output:

Original: map[a:1 b:2 c:3]
Copied: map[a:100 b:2 c:3]
  1. Using the copy Function (for slices of maps): If you have a slice of maps, you can use the copy function from the standard library to create a new slice with a copy of the original maps.
package main

import "fmt"

func main() {
    original := []map[string]int{
        {"a": 1, "b": 2, "c": 3},
        {"x": 10, "y": 20, "z": 30},
    }

    // Create a new slice and copy the maps.
    copied := make([]map[string]int, len(original))
    copy(copied, original)

    // Modify the copied map.
    copied[0]["a"] = 100

    // Output the original and copied slices.
    fmt.Println("Original:", original)
    fmt.Println("Copied:", copied)
}

Output:

Original: [map[a:1 b:2 c:3] map[x:10 y:20 z:30]]
Copied: [map[a:100 b:2 c:3] map[x:10 y:20 z:30]]

It’s important to note that these methods create a shallow copy of the map. If the map contains values that are pointers (e.g., slices or other maps), the copied map will still reference the same underlying data as the original. For deep copying (creating a new copy of all elements, including nested ones), you would need to manually traverse and copy the map deeply.

Choose the appropriate method based on your use case, and ensure that the copying method aligns with the behavior you need for your map and its values.

error: Content is protected !!