gob.Register() by type or for each variable?

huangapple go评论68阅读模式
英文:

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-

huangapple
  • 本文由 发表于 2015年7月17日 10:33:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/31467602.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定