Maps in Go are reference varieties, so to deep copy the contents of a map, you can not assign one occasion to a different. You are able to do this by creating a brand new, empty map after which iterating over the previous map in a for vary
loop to assign the suitable key-value pairs to the brand new map. It’s the easiest and most effective resolution to this drawback in Go.
package deal important
import "fmt"
func important() {
fruitRank := map[string]int{
"strawberry": 1,
"blueberry": 2,
"raspberry": 3,
}
// copy a map
fruitRankCopy := make(map[string]int)
for ok, v := vary fruitRank {
fruitRankCopy[k] = v
}
fruitRankCopy["apple"] = 4
fmt.Println("unique map")
fmt.Println(fruitRank)
fmt.Println("copied map")
fmt.Println(fruitRankCopy)
}
Output:
unique map
map[blueberry:2 raspberry:3 strawberry:1]
copied map
map[apple:4 blueberry:2 raspberry:3 strawberry:1]
As you see within the output, the copied map is a deep clone, and including new components doesn’t have an effect on the previous map.
Watch out when making a shallow copy by assigning one map to a different. On this case, a modification in both map will trigger a change within the information of each maps.
package deal important
import "fmt"
func important() {
fruitRank := map[string]int{
"strawberry": 1,
"blueberry": 2,
"raspberry": 3,
}
fruitRankShallowCopy := fruitRank
fruitRankShallowCopy["apple"] = 4
fmt.Println("unique map")
fmt.Println(fruitRank)
fmt.Println("copied map")
fmt.Println(fruitRankShallowCopy)
}
Output:
unique map
map[apple:4 blueberry:2 raspberry:3 strawberry:1]
copied map
map[apple:4 blueberry:2 raspberry:3 strawberry:1]