Standard library / encoding/gob

encoding/gob.GobEncoder

Implement GobEncode to define a custom byte representation, including private fields. Design a stable, versioned representation if data persists across releases. Expected stdout: '7\n'.

Formal Syntax & Structure

go syntaxgo
type GobEncoder interface {  GobEncode() ([]byte, error)}

Working Example

Example Snippetgo
package main
import (  "bytes"  "encoding/gob"  "errors"  "fmt")
func must(e error) {  if e != nil {    panic(e)  }}
type Item struct{ n byte }
func (v Item) GobEncode() ([]byte, error) { return []byte{v.n}, nil }func (v *Item) GobDecode(b []byte) error {  if len(b) != 1 {    return errors.New("bad length")  }  v.n = b[0]  return nil}func main() {  var _ gob.GobEncoder = Item{}  var buf bytes.Buffer  must(gob.NewEncoder(&buf).Encode(Item{7}))  var v Item  must(gob.NewDecoder(&buf).Decode(&v))  fmt.Println(v.n)}
Go Reference