4.6 利用protobuf生成的类来编码

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/golang/protobuf/proto"
  5. "protocolbuffer_excise/pb"
  6. )
  7. func main() {
  8. person := &pb.Person{
  9. Name: "Aceld",
  10. Age: 16,
  11. Emails: []string{"https://legacy.gitbook.com/@aceld", "https://github.com/aceld"},
  12. Phones: []*pb.PhoneNumber{
  13. &pb.PhoneNumber{
  14. Number: "13113111311",
  15. Type: pb.PhoneType_MOBILE,
  16. },
  17. &pb.PhoneNumber{
  18. Number: "14141444144",
  19. Type: pb.PhoneType_HOME,
  20. },
  21. &pb.PhoneNumber{
  22. Number: "19191919191",
  23. Type: pb.PhoneType_WORK,
  24. },
  25. },
  26. }
  27. data, err := proto.Marshal(person)
  28. if err != nil {
  29. fmt.Println("marshal err:", err)
  30. }
  31. newdata := &pb.Person{}
  32. err = proto.Unmarshal(data, newdata)
  33. if err != nil {
  34. fmt.Println("unmarshal err:", err)
  35. }
  36. fmt.Println(newdata)
  37. }