How to copy Map in Go?
How to copy Map in Go?
Copying a map in Go (Golang) involves creating a new map and then transferring the key-value pairs from the original map to the new one. This can be done in several ways, depending on whether you need a shallow copy or a deep copy of the map. Here are the methods to copy a map in Go:
A shallow copy of a map can be achieved by simply iterating over the original map and copying each key-value pair to a new map. This method is suitable when the values in the map are basic data types or if you do not need to duplicate the values that are reference types (like slices, maps, or pointers).
func main() {
originalMap := map[string]int{"Alice": 25, "Bob": 22, "John": 20}
newMap := make(map[string]int)
for key, value := range originalMap {
newMap[key] = value
}
fmt.Println("Original Map:", originalMap)
fmt.Println("Copied Map:", newMap)
}
A deep copy is necessary when the map contains reference types and you want the copied map to be entirely independent of the original map. Go does not have a built-in function for deep copying maps, but you can achieve this by using various techniques such as JSON marshaling and unmarshaling, creating custom functions, or using third-party libraries[1].
Here is an example using JSON for deep copying a map:
import (
"encoding/json"
"log"
)
func deepCopyMap(originalMap map[string]interface{}) (map[string]interface{}, error) {
var newMap map[string]interface{}
bytes, err := json.Marshal(originalMap)
if err != nil {
return nil, err
}
err = json.Unmarshal(bytes, &newMap)
if err != nil {
return nil, err
...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào