github.com/yukk001/go1.10.8@v0.0.0-20190813125351-6df2d3982e20/doc/progs/gobs2.go (about)

     1  // Copyright 2011 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 main
     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  func main() {
    25  	// Initialize the encoder and decoder.  Normally enc and dec would be
    26  	// bound to network connections and the encoder and decoder would
    27  	// run in different processes.
    28  	var network bytes.Buffer        // Stand-in for a network connection
    29  	enc := gob.NewEncoder(&network) // Will write to network.
    30  	dec := gob.NewDecoder(&network) // Will read from network.
    31  	// Encode (send) the value.
    32  	err := enc.Encode(P{3, 4, 5, "Pythagoras"})
    33  	if err != nil {
    34  		log.Fatal("encode error:", err)
    35  	}
    36  	// Decode (receive) the value.
    37  	var q Q
    38  	err = dec.Decode(&q)
    39  	if err != nil {
    40  		log.Fatal("decode error:", err)
    41  	}
    42  	fmt.Printf("%q: {%d,%d}\n", q.Name, *q.X, *q.Y)
    43  }