Decoding data is also very easy; it works in the same way as the other encoding packages we have already seen:
r := strings.NewReader("D\xff\x81\x03\x01\x01\tCharacter" +
"\x01\xff\x82\x00\x01\x04\x01\x04Name" +
"\x01\f\x00\x01\aSurname\x01\f\x00\x01\x03" +
"Job\x01\f\x00\x01\vYearOfBirth\x01\x04\x00" +
"\x00\x00*\xff\x82\x01\x06Albert\x01\bWilmarth" +
"\x01\x13assistant professor\x00")
d := gob.NewDecoder(r)
var c Character
if err := d.Decode(&c); err != nil {
log.Fatalln(err)
}
log.Printf("%+v", c)
Now, let's try to decode the same data in different structures—the original one and some with extra or missing fields. We will do this to see how the package behaves. Let's define a general decode function and pass different type of structs to the decoder:
func runDecode(data []byte, v interface{}) {
if err := gob.NewDecoder(bytes.NewReader(data)).Decode(v); err != nil {
log.Fatalln(err)
}
log.Printf("%+v", v)
}
Let's try to change the order of the fields in the struct to see whether the gob decoder still works:
runDecode(data, new(struct {
YearOfBirth int `gob:"year_of_birth,omitempty"`
Surname string `gob:"surname"`
Name string `gob:"name"`
Job string `gob:"job,omitempty"`
}))
Let's remove some fields:
runDecode(data, new(struct {
Name string `gob:"name"`
}))
Let's put a field in between:
runDecode(data, new(struct {
Name string `gob:"name"`
Surname string `gob:"surname"`
Country string `gob:"country"`
Job string `gob:"job,omitempty"`
YearOfBirth int `gob:"year_of_birth,omitempty"`
}))
We can see that the package keeps working even if we scramble, add, or remove the fields. But if we try to change the type of an existing field into another, it fails:
runDecode(data, new(struct {
Name []byte `gob:"name"`
}))