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

偶尔善良 提交于 2019-12-20 17:30:06

问题


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:


add

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

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




回答2:


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 :-)



来源:https://stackoverflow.com/questions/21934730/gob-type-not-registered-for-interface-mapstringinterface

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!