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

时间:2014-02-21 12:38:28

标签: go gob

gob无法对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))
}

是否可以在gob中编码map[string]interface{}? 我能用JSON编码它

2 个答案:

答案 0 :(得分:25)

添加

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

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

答案 1 :(得分:8)

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

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

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