I am trying to read a gob-encoded Go object into a variable of interface type. When I let gob
to the encoding itself, my code works (see below). In contrast, when I try to encode/decode the object manually, using MarshalBinary
and UnmarshalBinary
, my program crashes with the following message:
panic: interface conversion: interface is nil, not encoding.BinaryUnmarshaler [recovered]
panic: interface conversion: interface is nil, not encoding.BinaryUnmarshaler
What am I doing wrong?
Details. The interface I am using is given by
type Duck interface {
encoding.BinaryMarshaler
encoding.BinaryUnmarshaler
Quack()
}
The actual object I am encoding and trying to decode is
type A struct {
x byte
}
func (a *A) MarshalBinary() ([]byte, error) {
return []byte{a.x}, nil
}
func (a *A) UnmarshalBinary(data []byte) error {
a.x = data[0]
return nil
}
func (a *A) Quack() {
fmt.Println(a.x)
}
I have registered the type with gob using
gob.Register(&A{})
and encoding objects of type &A
seems to work fine. I try to gob-decode the object into an interface variable using the commands
dec := gob.NewDecoder(buf)
var duck2 Duck
dec.Decode(&duck2)
The last of these commands results in the panic shown above.
Full code is on play.golang.org.
Updated. Without the custom en-/decoder, the code works (after renaming a.x
to a.X
, to make the field globally visible): https://play.golang.org/p/y8nWNhObUwb