Maps.Copy
How can we duplicate a map, copying all the keys and values to a new map? In Go we can use a for-range
loop and build up another map, or we can use maps.Copy
.
A generic method, maps.Copy
can simplify programs by doing all the work in copying a map on its own. Each map will be separate in memory—adding to one will not affect the other.
This program creates 2 maps (dictionaries) with string
keys and string
values. It calls maps.Copy
to add the keys and values of one to the other.
maps.Copy
, the first argument is the target map we want to copy to, and the second is the source we want to copy from.maps.Copy
, the two maps have the same lengths—the same key counts.package main
import (
"fmt"
"maps"
)
func main() {
// Step 1: create a map of string keys and string values.
first := map[string]string {
"bird": "blue",
"cat": "yellow",
}
// Step 2: create an empty map of the same type keys and values.
second := map[string]string{}
// Step 3: use maps.Copy to copy the first map to the second map.
maps.Copy(second, first)
// Step 4: the maps have the same keys and values.
fmt.Println("Len of maps:", len(first), len(second))
// Step 5: add a key and value to one map, and this does not affect the other map.
second["snake"] = "green"
fmt.Println("Len of maps:", len(first), len(second))
}Len of maps: 2 2
Len of maps: 2 3
The "maps" package in Go is helpful for commonly-needed operations on maps. As long as the key and value types are equal in the maps, we can use maps.Copy
to duplicate maps.