为什么没有使用 protoc 3.17.* 生成方法,如果在 protobuf repo 中他们说应该生成?

Why has methods are not generated using protoc 3.17.* if in protobuf repo they say it should?

阅读此处:https://github.com/protocolbuffers/protobuf/blob/master/docs/field_presence.md#go-example Golang 示例:

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()

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

该文档有误,如此处所报告:https://github.com/golang/protobuf/issues/1336:

The documentation on https://github.com/protocolbuffers/protobuf/blob/master/docs/field_presence.md#go-example is incorrect. Using "optional" in proto3 makes the field be generated just as it would in proto2.

That doc is wrong. There are no Has methods in the generated code. Test for presence by comparing fields to nil.

Rewriting those examples correctly:

// 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 to fix that doc: protocolbuffers/protobuf#8788