How to Copy a Map in Go
This tutorial demonstrates how to copy a map in Go.
Copy a Map in Go
In Go, a map is a collection of unordered key-value pairs. It is popular because it allows for quick lookups and values that can be retrieved, updated, or deleted using keys.
Because maps in Go are reference types, you can’t deep replicate the contents of a map by assigning one instance to another. You can create a new, empty map and then add the appropriate key-value pairs to it using a for range loop.
In Go, it is the most straightforward and efficient solution to this problem.
The cloned map is a deep clone in this example output, and adding additional pieces does not affect the original map.
Example 1:
package main
import "fmt"
func main() {
dark := map[string]int{
"Jay": 1,
"Adam": 2,
"Eve": 3,
}
// copy a map
darkch := make(map[string]int)
for k, v := range dark {
darkch[k] = v
}
darkch["Jonas"] = 4
fmt.Println("Original")
fmt.Println(dark)
fmt.Println("Copied")
fmt.Println(darkch)
}
Output:
Original
map[Adam:2 Eve:3 Jay:1]
Copied
map[Adam:2 Eve:3 Jay:1 Jonas:4]
We map the name and roll number to the original map in this example.
Example 2:
package main
import (
"fmt"
)
func main() {
studs := map[string]int{
"Jay": 1,
"Adam": 2,
"Eve": 3,
}
studs_tmp := make(map[string]int)
for name, roll_no := range studs {
studs_tmp[name] = roll_no
}
for name, roll_no := range studs_tmp {
fmt.Println("Name: ", name, ", roll_no: ", roll_no)
}
}
Output:
Name: Jay , roll_no: 1
Name: Adam , roll_no: 2
Name: Eve , roll_no: 3