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.
Example. 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.
Step 1 We create a map with 2 keys, each with an associated value. The keys and values are all strings.
Step 5 We add a new key to the second map. This does not affect the first map, so now the 2 maps have different 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
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.