Search code examples
goprotocol-buffersprotoprotoc

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


Reading here: https://github.com/protocolbuffers/protobuf/blob/master/docs/field_presence.md#go-example the Golang 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);
}

if I use:

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

with:

syntax = "proto3";

package example;

message MyPlayer {
  uint64 id = 1;
  optional string description = 2;
  uint32 qty = 3;
  optional uint64 age = 4;
}

it doesn't generate any has<T>() method.

Why?

// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
//  protoc-gen-go v1.26.0
//  protoc        v3.17.3

Am I wrong if I use MyPlayer generated proto fields instead of methods?

Example:

if MyPlayer.description != nil {
  description = *MyPlayer.description
}

instead of

description = MyPlayer.GetDescription()

which is not what I want (I want to detect nil values).


Solution

  • That docs is wrong, as reported here: 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