gpt4 book ai didi

gob.Register() 按类型或每个变量?

转载 作者:IT王子 更新时间:2023-10-29 01:42:36 24 4
gpt4 key购买 nike

我在我的代码中做这样的事情

test1 = make(map[string]interface{})
test2 = make(map[string]interface{})
test3 = make(map[string]interface{})
test4 = make(map[string]interface{})

gob.Register(test1)
gob.Register(test2)
gob.Register(test3)
gob.Register(test4)

它可以编译,但我应该这样做吗?或者我是否只需要注册其中一个,因为它们具有相同的类型?

gob.Register(test1)

最佳答案

根据 https://golang.org/pkg/encoding/gob/#Register -

Register records a type, identified by a value for that type, under its internal type name.

注册空类型——例如

gob.Register(map[string]interface{}{})

完整示例:

func main() {
gob.Register(map[string]interface{}{})
a := map[string]interface{}{
"X": 1,
"Greeting": "hello",
}
buf := new(bytes.Buffer)
err := gob.NewEncoder(buf).Encode(a)
if err != nil {
log.Fatal(err)
}

fmt.Println(buf.Bytes())

val := make(map[string]interface{})
err = gob.NewDecoder(buf).Decode(&val)
if err != nil {
log.Fatal(err)
}

fmt.Printf("%+v\n", val)
}

在这里运行:http://play.golang.org/p/e5vXER_dz-

关于gob.Register() 按类型或每个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31467602/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com