Deep Copying and Clearing Maps in Go
When working with associative data structures, it's often necessary to create a deep copy of a map and then clear the original to accept new values. In Go, however, simply assigning the reference to a map does not create a deep copy, leading to issues with clearing the original map.
The Problem
Consider the following code:
for something := range fruits { aMap := make(map[string]aStruct) aSuperMap := make(map[string]map[string]aStruct) for x := range something { aMap[x] = aData aSuperMap[y] = aMap delete(aMap, x) } // Save aSuperMap }
In this code, we attempt to create a deep copy of aMap into aSuperMap and then clear aMap so that it can take new values. However, deleting an element from aMap also deletes it from aSuperMap because both maps are referencing the same underlying data.
The Solution
To create a true deep copy of a map in Go, a for loop must be used to manually copy each key and value pair from the original map to the new map:
for k, v := range originalMap { newMap[k] = v }
This will create a new map, newMap, that is independent of the original map, originalMap.
Clearing the Original Map
After creating a deep copy of the map, the original map can be cleared using the built-in len() function:
length := len(aMap) for i := 0; i < length; i++ { for key := range aMap { delete(aMap, key) } }
This will remove all elements from the aMap while leaving the contents of aSuperMap intact.
The above is the detailed content of How to Deep Copy and Clear Maps in Go?. For more information, please follow other related articles on the PHP Chinese website!