golang - gob编码接口错误

时间:2014-07-01 10:31:52

标签: go

我有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)


}

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

1 个答案:

答案 0 :(得分:4)

您需要预先register您的界面:

gob.Register(user)
enc = gob.NewEncoder(m)
err = enc.Encode(data)