32-protobuf中使用wrapValue类型

15 阅读1分钟

protobuf中使用wrapValue类型

  • go get google/protobuf/wrappers.proto
  • 用来解决"零值问题": 本质是结构体指针
syntax = "proto3;

package = "api";

option go_package="protobuf_demo/api";

import "google/protobuf/wrappers.proto";

message Book {
  string title = 1;
  string author = 2;
  goolgle.protobuf.Int64Value price = 3;
  goolgle.protobuf.StringValue memo = 5;
  //goolgle.protobuf.DoubleValue price2 = 4;
}
  • 生成旁边.pb.go文件
  • 使用
package main

import "google.golang.org/protobuf/types/known/wrapperspb";

func wrapValue() {
   book := api.Book{
      Title: "哈哈哈",
      Price: &wrapperspb.Int64Value{Value: 8888},
      Memo: &wrapperspb.StringValue{Value: "哈哈哈"},
   }
   
   if book.Price == nil {
      // 没有给price赋值
      
   }else {
     // 赋值了
     book.GetPrice().GetValue()
   }
   
   if book.GetMemo() != nil {
      // 设置了memo
      book.GetMemo().GetValue()
   }
}