Explain gob and schema evolution
Explain gob and schema evolution
encoding/gob is a Go-oriented binary stream format with type information. An Encoder writes values and a Decoder reads them. It can match exported struct fields by name rather than requiring identical struct names or field ordering. Use it for trusted Go-to-Go data, not a general untrusted network interchange format.
package main
import ( "bytes" "encoding/gob" "fmt")
func check(e error) { if e != nil { panic(e) }}
type Old struct { Name string Qty int}type New struct { Qty int Name string Note string}
func main() { var b bytes.Buffer check(gob.NewEncoder(&b).Encode(Old{Name: "Tea", Qty: 3})) var p New check(gob.NewDecoder(&b).Decode(&p)) fmt.Printf("%s %d %q\n", p.Name, p.Qty, p.Note)}The two matching fields have compatible types. Note is absent in the old sender and stays at its zero value in this fresh receiver. Adding an optional exported field may be compatible, but changing a field to an incompatible type is not. Use explicit migration rules and compatibility tests; decode into fresh destinations because existing values are not necessarily cleared.
Expected output:
Tea 3 ""Detect incompatible field types
package main
import ( "bytes" "encoding/gob" "fmt")
func check(e error) { if e != nil { panic(e) }}
func main() { var b bytes.Buffer check(gob.NewEncoder(&b).Encode(struct{ Qty int }{3})) var p struct{ Qty string } e := gob.NewDecoder(&b).Decode(&p) fmt.Println(e != nil)}The integer field cannot be decoded into a string field of the same name. Reject the failed result. Gob is not hardened for hostile inputs; even a byte limit alone does not bound all decoding allocations. Prefer a deliberately constrained format at untrusted boundaries and verify both directions of any schema change.
Expected output:
trueTry it locally
Encode struct{Name string;Extra int}{"Ada",7} with gob, decode into a fresh struct{Name string}, and print Name.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Serialization 09: Explain gob and schema evolution
Check the lesson objective before moving on.
How does gob match compatible struct fields?
Is gob designed to safely decode arbitrary hostile input?