为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
牧羊人nacy 2022-09-12 16:43:04
阅读这里: 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()这不是我想要的(我想检测零值)。
查看完整描述

1 回答

?
Qyouu

TA贡献1786条经验 获得超11个赞

该文档是错误的,如此处所述:https://github.com/golang/protobuf/issues/1336

有关 https://github.com/protocolbuffers/protobuf/blob/master/docs/field_presence.md#go-example 的文档不正确。在 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 {

  // "Clear" the field:

  m.Foo = 0

} else {

  // Default value: field may not have been present.

  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 {

  // Clear the field:

  m.Foo = nil

} else {

  // Field is not present, so set it.

  m.Foo = proto.Int32(1)

}

PR来修复该文档:协议缓冲器/原型buff#8788


查看完整回答
反对 回复 2022-09-12
  • 1 回答
  • 0 关注
  • 114 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号