Maps in Go are reference types, so to deep copy the contents of a map, you cannot assign one instance to another. You can do this by creating a new, empty map and then iterating over the old map in a for range
loop to assign the appropriate key-value pairs to the new map. It is the simplest and most efficient solution to this problem in Go.
package main
import "fmt"
func main() {
fruitRank := map[string]int{
"strawberry": 1,
"blueberry": 2,
"raspberry": 3,
}
// copy a map
fruitRankCopy := make(map[string]int)
for k, v := range fruitRank {
fruitRankCopy[k] = v
}
fruitRankCopy["apple"] = 4
fmt.Println("original map")
fmt.Println(fruitRank)
fmt.Println("copied map")
fmt.Println(fruitRankCopy)
}
Output:
original map
map[blueberry:2 raspberry:3 strawberry:1]
copied map
map[apple:4 blueberry:2 raspberry:3 strawberry:1]
As you see in the output, the copied map is a deep clone, and adding new elements does not affect the old map.
Be careful when making a shallow copy by assigning one map to another. In this case, a modification in either map will cause a change in the data of both maps.
package main
import "fmt"
func main() {
fruitRank := map[string]int{
"strawberry": 1,
"blueberry": 2,
"raspberry": 3,
}
fruitRankShallowCopy := fruitRank
fruitRankShallowCopy["apple"] = 4
fmt.Println("original map")
fmt.Println(fruitRank)
fmt.Println("copied map")
fmt.Println(fruitRankShallowCopy)
}
Output:
original map
map[apple:4 blueberry:2 raspberry:3 strawberry:1]
copied map
map[apple:4 blueberry:2 raspberry:3 strawberry:1]