Home > Backend Development > Golang > How to Create Deep Copies of Maps in Go?

How to Create Deep Copies of Maps in Go?

Patricia Arquette
Release: 2024-11-29 02:01:14
Original
209 people have browsed it

How to Create Deep Copies of Maps in Go?

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

  • encoding/gob: This library enables you to encode and decode arbitrary data structures, including maps. By encoding the original map and decoding it into a new variable, you can create a deep copy.
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)
}
Copy after login

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!

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