我有golang gob编码的问题。当我使用struct编码接口时出错。
我的代码:
package main
import (
"bytes"
"encoding/gob"
"fmt"
)
type Data struct {
Id int
D interface{}
}
type User struct {
Name string
Age int
}
func main() {
//work well-----------
data := Data{
Id:99,
D: []int{1,2,3},
}
m := new(bytes.Buffer)
enc := gob.NewEncoder(m)
err := enc.Encode(data)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(m)
//-------------------
//error -------------
user := User{
Name: "Lei",
Age: 25,
}
data = Data{
Id: 100,
D: user,
}
m = new(bytes.Buffer)
enc = gob.NewEncoder(m)
err = enc.Encode(data)
//err - gob: type not registered for interface: main.User
if err != nil {
fmt.Println(err)
return
}
fmt.Println(m)
}
答案 0 :(得分:4)
您需要预先register您的界面:
gob.Register(user)
enc = gob.NewEncoder(m)
err = enc.Encode(data)