Gob解码器返回EOF错误

时间:2015-10-12 04:45:26

标签: go gob

我正在尝试实现基于接口的消息队列,其中作业以字节形式推送到redis队列。但是在尝试解码字节流时,我一直收到EOF错误。

https://play.golang.org/p/l9TBvcn9qg

有人能指出我正确的方向吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

在Go Playground示例中,您正在尝试对接口进行编码,并且接口没有具体的实现。如果从A结构中删除界面,那应该有效。如下所示:

package main

import "fmt"
import "encoding/gob"
import "bytes"

type testInterface interface{}

type A struct {
  Name string
  Interface *B // note this change here
}

type B struct {
  Value string
}

func main() {
  var err error
  test := &A {
    Name: "wut",
    Interface: &B{Value: "BVALUE"},
  }
  buf := bytes.NewBuffer([]byte{})
  enc := gob.NewEncoder(buf)
  dec := gob.NewDecoder(buf)

  // added error checking as per Mark's comment
  err = enc.Encode(test)
  if err != nil {
    panic(err.Error())
  }

  result := &A{}
  err := dec.Decode(result)
  fmt.Printf("%+v\n", result)
  fmt.Println("Error is:", err)
  fmt.Println("Hello, playground")
}

另外,作为旁注,您会看到某种类型的输出,如下所示:&{Name:wut Interface:0x1040a5a0}因为A引用了对B结构的引用。要进一步清理它:

type A struct{
  Name string
  Interface B // no longer a pointer
}

func main() {
   // ...
   test := &A{Name: "wut", Interface: B{Value: "BVALUE"}}
   // ...
}

答案 1 :(得分:0)

从Mark上面找到问题的答案。我忘了做gob.Register(B{})

https://play.golang.org/p/7rQDHvMhD7

相关问题