英文:
gob.Register() by type or for each variable?
问题
我在我的代码中做了类似这样的事情:
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)
英文:
I am doing something like this in my code
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)
It compiles but am I suppose to be doing it that way? Or do I just need to register one of them because they have the same type?
gob.Register(test1)
答案1
得分: 2
根据https://golang.org/pkg/encoding/gob/#Register的说明:
Register函数会使用类型的值来标识该类型,并将其记录在内部类型名称下。
注册空类型,例如:
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-
英文:
As per https://golang.org/pkg/encoding/gob/#Register -
> Register records a type, identified by a value for that type, under its internal type name.
Register the empty type - e.g.
gob.Register(map[string]interface{}{})
Full example:
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)
}
Run it here: http://play.golang.org/p/e5vXER_dz-
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论