是否有内置功能去制作任意地图的副本? [英] Is there a built in function in go for making copies of arbitrary maps?
问题描述
我可以用手写一个,但之前我发现我正在寻找一个类似的问题,当我想对地图进行深度比较时,似乎已经有了一个功能!同样,也许我想知道是否有内置或某些库或包在golang中制作地图的深层副本。我相信我不是第一个想在地图上制作地图副本的人。
通过复制,我可以创建两个不同的变量,引用不同的地图即使它们是相同的内容明智的。
对于更一般的答案,您可以编码您的地图并将其解码一个带有编码/ gob 的新变量。
这种方式是它甚至可以在更复杂的数据结构上工作,比如包含一片地图的一片结构。
包主要
导入(
字节
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(解码错误:,err)
}
fmt.Println(cpy:,cpy)// key:3 clef:5
cpy [key] = 2
fmt.Println(cpy:,cpy)// key:2谱号:5
fmt.Println(ori:,ori)// key:3谱号:5
}
如果您想了解更多有关gobs的信息,请点击关于它的博客文章
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 when I wanted to make a deep comparison of maps and there seemed to be a function already built in for that! So similarly, maybe I was wondering if there was an built in or some library or package for making deep copies of maps in golang. I am sure I am not the first person to want to make copies of maps in go.
By copy I mean you can create two different variables that reference a different map in memory even though they are the same content wise.
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.
这篇关于是否有内置功能去制作任意地图的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!