gobs2.go 987 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. package main
  5. import (
  6. "bytes"
  7. "encoding/gob"
  8. "fmt"
  9. "log"
  10. )
  11. type P struct {
  12. X, Y, Z int
  13. Name string
  14. }
  15. type Q struct {
  16. X, Y *int32
  17. Name string
  18. }
  19. func main() {
  20. // Initialize the encoder and decoder. Normally enc and dec would be
  21. // bound to network connections and the encoder and decoder would
  22. // run in different processes.
  23. var network bytes.Buffer // Stand-in for a network connection
  24. enc := gob.NewEncoder(&network) // Will write to network.
  25. dec := gob.NewDecoder(&network) // Will read from network.
  26. // Encode (send) the value.
  27. err := enc.Encode(P{3, 4, 5, "Pythagoras"})
  28. if err != nil {
  29. log.Fatal("encode error:", err)
  30. }
  31. // Decode (receive) the value.
  32. var q Q
  33. err = dec.Decode(&q)
  34. if err != nil {
  35. log.Fatal("decode error:", err)
  36. }
  37. fmt.Printf("%q: {%d,%d}\n", q.Name, *q.X, *q.Y)
  38. }