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

后端 未结 4 1991
心在旅途
心在旅途 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: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.

提交回复
热议问题