gob: 未为接口注册类型:map[string]interface {}

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

gob: type not registered for interface: map[string]interface {}

问题

gob无法对map[string]interface{}进行编码。

错误信息为:gob: type not registered for interface: map[string]interface {}。

在Go语言中,gob包无法直接对map[string]interface{}类型进行编码。但是你可以使用JSON来对其进行编码。

英文:

gob fails to encode map[string]interface{}

gob: type not registered for interface: map[string]interface {}

http://play.golang.org/p/Si4hd8I0JE

package main

import (
	"bytes"
	"encoding/gob"
	"encoding/json"
	"fmt"
	"log"
)

func CloneObject(a, b interface{}) []byte {
	buff := new(bytes.Buffer)
	enc := gob.NewEncoder(buff)
	dec := gob.NewDecoder(buff)
	err := enc.Encode(a)
	if err != nil {
		log.Panic("e1: ", err)
	}
	b1 := buff.Bytes()
	err = dec.Decode(b)
	if err != nil {
		log.Panic("e2: ", err)
	}
	return b1
}

func main() {
	var a interface{}
	a = map[string]interface{}{"X": 1}
	b2, err := json.Marshal(&a)
	fmt.Println(string(b2), err)

	var b interface{}
	b1 := CloneObject(&a, &b)
	fmt.Println(string(b1))
}

Is it possible to encode map[string]interface{} in gob?
I am able to encode it with JSON

答案1

得分: 50

添加

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

http://play.golang.org/p/Dd3IzJgl0A

英文:

add

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

http://play.golang.org/p/Dd3IzJgl0A

答案2

得分: 9

可能是的,但是你必须事先注册你的类型。请参考http://golang.org/pkg/encoding/gob/#Register。

详细信息已在http://golang.org/pkg/encoding/gob/#hdr-Encoding_Details中记录。

(查看Go文档确实会有帮助 :-))

英文:

Probably yes, but you do have to Register your type beforehand. See http://golang.org/pkg/encoding/gob/#Register.

The details are documented in http://golang.org/pkg/encoding/gob/#hdr-Encoding_Details

(It really does help to look at the Go documentation gob: 未为接口注册类型:map[string]interface {}

huangapple
  • 本文由 发表于 2014年2月21日 20:38:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/21934730.html
匿名

发表评论

匿名网友

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

确定