gob1.go 870 B

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