...

Source file src/encoding/gob/example_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  type P struct {
		15  	X, Y, Z int
		16  	Name		string
		17  }
		18  
		19  type Q struct {
		20  	X, Y *int32
		21  	Name string
		22  }
		23  
		24  // This example shows the basic usage of the package: Create an encoder,
		25  // transmit some values, receive them with a decoder.
		26  func Example_basic() {
		27  	// Initialize the encoder and decoder. Normally enc and dec would be
		28  	// bound to network connections and the encoder and decoder would
		29  	// run in different processes.
		30  	var network bytes.Buffer				// Stand-in for a network connection
		31  	enc := gob.NewEncoder(&network) // Will write to network.
		32  	dec := gob.NewDecoder(&network) // Will read from network.
		33  
		34  	// Encode (send) some values.
		35  	err := enc.Encode(P{3, 4, 5, "Pythagoras"})
		36  	if err != nil {
		37  		log.Fatal("encode error:", err)
		38  	}
		39  	err = enc.Encode(P{1782, 1841, 1922, "Treehouse"})
		40  	if err != nil {
		41  		log.Fatal("encode error:", err)
		42  	}
		43  
		44  	// Decode (receive) and print the values.
		45  	var q Q
		46  	err = dec.Decode(&q)
		47  	if err != nil {
		48  		log.Fatal("decode error 1:", err)
		49  	}
		50  	fmt.Printf("%q: {%d, %d}\n", q.Name, *q.X, *q.Y)
		51  	err = dec.Decode(&q)
		52  	if err != nil {
		53  		log.Fatal("decode error 2:", err)
		54  	}
		55  	fmt.Printf("%q: {%d, %d}\n", q.Name, *q.X, *q.Y)
		56  
		57  	// Output:
		58  	// "Pythagoras": {3, 4}
		59  	// "Treehouse": {1782, 1841}
		60  }
		61  

View as plain text