...

Source file src/encoding/gob/example_encdec_test.go

Documentation: encoding/gob

		 1  // Copyright 2013 The Go Authors. All rights reserved.
		 2  // Use of this source code is governed by a BSD-style
		 3  // license that can be found in the LICENSE file.
		 4  
		 5  package gob_test
		 6  
		 7  import (
		 8  	"bytes"
		 9  	"encoding/gob"
		10  	"fmt"
		11  	"log"
		12  )
		13  
		14  // The Vector type has unexported fields, which the package cannot access.
		15  // We therefore write a BinaryMarshal/BinaryUnmarshal method pair to allow us
		16  // to send and receive the type with the gob package. These interfaces are
		17  // defined in the "encoding" package.
		18  // We could equivalently use the locally defined GobEncode/GobDecoder
		19  // interfaces.
		20  type Vector struct {
		21  	x, y, z int
		22  }
		23  
		24  func (v Vector) MarshalBinary() ([]byte, error) {
		25  	// A simple encoding: plain text.
		26  	var b bytes.Buffer
		27  	fmt.Fprintln(&b, v.x, v.y, v.z)
		28  	return b.Bytes(), nil
		29  }
		30  
		31  // UnmarshalBinary modifies the receiver so it must take a pointer receiver.
		32  func (v *Vector) UnmarshalBinary(data []byte) error {
		33  	// A simple encoding: plain text.
		34  	b := bytes.NewBuffer(data)
		35  	_, err := fmt.Fscanln(b, &v.x, &v.y, &v.z)
		36  	return err
		37  }
		38  
		39  // This example transmits a value that implements the custom encoding and decoding methods.
		40  func Example_encodeDecode() {
		41  	var network bytes.Buffer // Stand-in for the network.
		42  
		43  	// Create an encoder and send a value.
		44  	enc := gob.NewEncoder(&network)
		45  	err := enc.Encode(Vector{3, 4, 5})
		46  	if err != nil {
		47  		log.Fatal("encode:", err)
		48  	}
		49  
		50  	// Create a decoder and receive a value.
		51  	dec := gob.NewDecoder(&network)
		52  	var v Vector
		53  	err = dec.Decode(&v)
		54  	if err != nil {
		55  		log.Fatal("decode:", err)
		56  	}
		57  	fmt.Println(v)
		58  
		59  	// Output:
		60  	// {3 4 5}
		61  }
		62  

View as plain text