使用go lang在protobuf中创建数组指针

时间:2018-10-09 15:42:20

标签: go protocol-buffers grpc

我是grpc的新手,我已经创建了一个名为Accounts的服务的原型文件,具有方法名称GetValidators,我想在使用(gogoproto.customtype)的消息中创建指向BondedValidators和UnbondingValidators变量的空白指针[] *。

syntax = 'proto3';
package grpc;

import "github.com/gogo/protobuf/gogoproto/gogo.proto";
import "google/api/annotations.proto";
import "google/protobuf/struct.proto";

option (gogoproto.marshaler_all) = false;
option (gogoproto.unmarshaler_all) = false;
option (gogoproto.sizer_all) = false;
option (gogoproto.goproto_registration) = true;
option (gogoproto.messagename_all) = true;
option (gogoproto.protosizer_all) =false;

service Accounts {
rpc GetValidators(Empty) returns (ValidatorOutput);
}

message ValidatorOutput {
uint64 BlockHeight  = 1 ;       
repeated google.protobuf.ListValue  BondedValidators  = 2   [(gogoproto.customtype) = "github.com/gallactic/gallactic/core/validator.Validator", (gogoproto.nullable) = false];
repeated google.protobuf.ListValue  UnbondingValidators  = 3 [(gogoproto.customtype) = "github.com/gallactic/gallactic/core/validator.Validator", (gogoproto.nullable) = false];
}

无论何时使用以下代码:

protoc -I/usr/local/include -I. -I$GOPATH/src-I$GOPATH/src/github.com/grpcecosystem/grpc-gateway/third_party/googleapis --gofast_out=plugins=grpc:./ ./protobuf/account.proto

它在.pb.go文件中生成输出,带有三个额外的变量

type ValidatorOutput struct {
BlockHeight          uint64                        `protobuf:"varint,1,opt,name=BlockHeight,proto3" json:"BlockHeight,omitempty"`
BondedValidators     []github_com_gallactic_gallactic_core_validator.Validator `protobuf:"bytes,2,rep,name=BondedValidators,customtype=github.com/gallactic/gallactic/core/validator.Validator" json:"BondedValidators"`
UnbondingValidators  []github_com_gallactic_gallactic_core_validator.Validator `protobuf:"bytes,3,rep,name=UnbondingValidators,customtype=github.com/gallactic/gallactic/core/validator.Validator" json:"UnbondingValidators"`
XXX_NoUnkeyedLiteral struct{}                                                   `json:"-"`
XXX_unrecognized     []byte                                                     `json:"-"`
XXX_sizecache        int32                                                      `json:"-"`
 }

输出应为

type ValidatorOutput struct {
BlockHeight          uint64                                                     `protobuf:"varint,1,opt,name=BlockHeight,proto3" json:"BlockHeight,omitempty"`
BondedValidators     []*github_com_gallactic_gallactic_core_validator.Validator `protobuf:"bytes,2,rep,name=BondedValidators,customtype=github.com/gallactic/gallactic/core/validator.Validator" json:"BondedValidators"`
UnbondingValidators  []*github_com_gallactic_gallactic_core_validator.Validator `protobuf:"bytes,3,rep,name=UnbondingValidators,customtype=github.com/gallactic/gallactic/core/validator.Validator" json:"UnbondingValidators"`
}  

1 个答案:

答案 0 :(得分:1)

当您使用nullable=false选项时,gogo proto将删除指针,因此您需要从proto定义中删除(gogoproto.nullable) = false选项,以使其生成[] * foo