Is there a built in function in go for making copies of arbitrary maps?

后端 未结 4 1971
心在旅途
心在旅途 2021-01-04 04:19

Is there a built in function in go for making copies of arbitrary maps?

I would be able to write one by hand but I found out earlier I was looking a similar question

相关标签:
4条回答
  • 2021-01-04 04:39

    To add to the answer by Simpfally, some gotchas with encoding/gob are that with structs, only exported fields are copied. And channels can't be encoded.

    0 讨论(0)
  • 2021-01-04 04:40

    For a more general answer, you can encode your map and decode it in a new variable with encoding/gob.

    The advantages of this way is that it'll even work on more complex data structure, like a slice of struct containing a slice of maps.

    package main
    
    import (
        "bytes"
        "encoding/gob"
        "fmt"
        "log"
    )
    
    func main() {
        ori := map[string]int{
            "key":  3,
            "clef": 5,
        }
    
        var mod bytes.Buffer
        enc := gob.NewEncoder(&mod)
        dec := gob.NewDecoder(&mod)
    
        fmt.Println("ori:", ori) // key:3 clef:5
        err := enc.Encode(ori)
        if err != nil {
            log.Fatal("encode error:", err)
        }
    
        var cpy map[string]int
        err = dec.Decode(&cpy)
        if err != nil {
            log.Fatal("decode error:", err)
        }
    
        fmt.Println("cpy:", cpy) // key:3 clef:5
        cpy["key"] = 2
        fmt.Println("cpy:", cpy) // key:2 clef:5
        fmt.Println("ori:", ori) // key:3 clef:5
    }
    

    If you want to know more about gobs, there is a go blog post about it.

    0 讨论(0)
  • 2021-01-04 04:48

    Copying a map is a few, trivial lines of code. Just write the code and enjoy letting go of the idea that every simple piece of code has to be in a library!

    original := map[string]int{
        "Hello": 4,
        "World": 123,
    }
    
    copy := map[string]int{}
    for k, v := range original {
        copy[k] = v
    }
    
    0 讨论(0)
  • 2021-01-04 04:53

    No, there is no built-in one-liner for map deep copy.

    However, there is an iterative solution as well as a generic package for deep copy.

    0 讨论(0)
提交回复
热议问题