gob_test.go 692 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package gob
  2. import (
  3. "bytes"
  4. "encoding/gob"
  5. "fmt"
  6. "testing"
  7. )
  8. type msgData struct {
  9. X, Y, Z int
  10. Name string
  11. Value any
  12. }
  13. type msgDataValue struct {
  14. Name string
  15. }
  16. func TestGOB(t *testing.T) {
  17. gob.Register(msgDataValue{})
  18. var buf bytes.Buffer
  19. enc := gob.NewEncoder(&buf)
  20. //
  21. sendMsg := msgData{
  22. X: 3,
  23. Y: 4,
  24. Z: 5,
  25. Name: "name",
  26. Value: msgDataValue{Name: "DataValue"},
  27. }
  28. fmt.Println("原始数据:", sendMsg)
  29. err := enc.Encode(&sendMsg)
  30. fmt.Println(err)
  31. fmt.Println("传递的编码数据为:", buf)
  32. dec := gob.NewDecoder(&buf)
  33. sendMsgDecode := msgData{}
  34. err = dec.Decode(&sendMsgDecode)
  35. fmt.Println(err)
  36. fmt.Println(sendMsgDecode)
  37. }