Creating Deep Copies of Maps in Go
While you can manually create a copy of a map, it may be more convenient to utilize built-in functions or libraries.
Built-In Functions
Unfortunately, there is no built-in function specifically for making copies of arbitrary maps in Go.
Libraries and Packages
import ( "bytes" "encoding/gob" "fmt" ) func main() { ori := map[string]int{ "key": 3, "clef": 5, } // Encode the original map var mod bytes.Buffer enc := gob.NewEncoder(&mod) err := enc.Encode(ori) if err != nil { fmt.Println("Failed to encode map:", err) return } // Decode the encoded map into a new variable (deep copy) var cpy map[string]int dec := gob.NewDecoder(&mod) err = dec.Decode(&cpy) if err != nil { fmt.Println("Failed to decode map:", err) return } // Modify the copied map to demonstrate they are independent cpy["key"] = 2 fmt.Println("Original map:", ori) fmt.Println("Copied map:", cpy) }
By utilizing one of these approaches, you can conveniently create deep copies of maps in Go.
The above is the detailed content of How to Create Deep Copies of Maps in Go?. For more information, please follow other related articles on the PHP Chinese website!