为什么没有使用protoc 3.17.*生成方法,如果在protobuf存储库中他们说应该这样做?

阅读这里: https://github.com/protocolbuffers/protobuf/blob/master/docs/field_presence.md#go-example 高浪的例子:


m := GetProto()

if (m.HasFoo()) {

  // Clear the field:

  m.Foo = nil

} else {

  // Field is not present, so set it.

  m.Foo = proto.Int32(1);

}

如果我使用:


protoc pkg/user.proto --go_out=. --go_opt=module=my_app --go-grpc_out=. --go-grpc_opt=module=my_app

跟:


syntax = "proto3";


package example;


message MyPlayer {

  uint64 id = 1;

  optional string description = 2;

  uint32 qty = 3;

  optional uint64 age = 4;

}

它不会生成任何方法。has<T>()


为什么?


// Code generated by protoc-gen-go. DO NOT EDIT.

// versions:

//  protoc-gen-go v1.26.0

//  protoc        v3.17.3

如果我使用生成的原型字段而不是方法,我错了吗?MyPlayer


例:


if MyPlayer.description != nil {

  description = *MyPlayer.description

}

而不是


description = MyPlayer.GetDescription()

这不是我想要的(我想检测零值)。


牧羊人nacy
浏览 115回答 1
1回答

Qyouu

该文档是错误的,如此处所述:https://github.com/golang/protobuf/issues/1336:有关&nbsp;https://github.com/protocolbuffers/protobuf/blob/master/docs/field_presence.md#go-example&nbsp;的文档不正确。在 proto3 中使用“可选”可以生成字段,就像在 proto2 中一样。该文档是错误的。生成的代码中没有方法。通过将字段与 进行比较来测试是否存在。Hasnil正确重写这些示例:// Field foo does not have presence.// If field foo is not 0, set it to 0.// If field foo is 0, set it to 1.m := GetProto()if m.Foo != 0 {&nbsp; // "Clear" the field:&nbsp; m.Foo = 0} else {&nbsp; // Default value: field may not have been present.&nbsp; m.Foo = 1}// Field foo has presence.// If foo is set, clear it.// If foo is not set, set it to 1.m := GetProto()if m.Foo != nil {&nbsp; // Clear the field:&nbsp; m.Foo = nil} else {&nbsp; // Field is not present, so set it.&nbsp; m.Foo = proto.Int32(1)}PR来修复该文档:协议缓冲器/原型buff#8788
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go