Home > Backend Development > Golang > How to Deep Copy and Clear Maps in Go?

How to Deep Copy and Clear Maps in Go?

Mary-Kate Olsen
Release: 2024-12-29 17:46:11
Original
314 people have browsed it

How to Deep Copy and Clear Maps in Go?

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
}
Copy after login

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
}
Copy after login

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)
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template