Deep Copying a Map without Corrupting the Original
In Go, attempting to copy a map by assigning a reference like aSuperMap[y] = aMap can lead to unintended consequences. To create an associative map without affecting the original, deep copying is necessary.
The Problem
The example provided attempts to copy the contents of aMap into aSuperMap and then clear aMap. However, deleting an entry from aMap (delete(aMap, x)) also removes its reference from aSuperMap. This results in the supermap containing duplicate data or becoming inconsistent.
Solution: Deep Copying
To avoid modifying the original map when making changes to the copy, deep copying is used. In a for loop:
for k, v := range originalMap { newMap[k] = v }
Each key-value pair from originalMap is individually copied into newMap. This process creates a new and independent map that is not linked to the original. The original map can then be cleared without affecting the copy.
Example
The following example demonstrates deep copying a map:
originalMap := map[string]int{"one": 1, "two": 2} // Deep copy originalMap into newMap newMap := make(map[string]int) for k, v := range originalMap { newMap[k] = v } // Clear the original map originalMap = make(map[string]int) // Verify that newMap is independent of originalMap newMap["three"] = 3 fmt.Println(newMap) // {one: 1, two: 2, three: 3} fmt.Println(originalMap) // {}
In this example, deep copying allows newMap to be modified and extended independently of originalMap, ensuring that the integrity of both maps is maintained.
The above is the detailed content of How to Deep Copy a Go Map Without Affecting the Original?. For more information, please follow other related articles on the PHP Chinese website!