Is there a built in function in go for making copies of arbitrary maps? -
is there built in function in go making copies of arbitrary maps?
i able write 1 hand found out earlier looking similar question when wanted make deep comparison of maps , there seemed function built in that! similarly, maybe wondering if there built in or library or package making deep copies of maps in golang. sure not first person want make copies of maps in go.
by copy mean can create 2 different variables reference different map in memory though same content wise.
for more general answer, can encode map , decode in new variable encoding/gob.
the advantages of way it'll work on more complex data structure, slice of struct containing 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 want know more gobs, there go blog post it.
Comments
Post a Comment