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
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.
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.
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
}
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.