How is protobuf 3 singular different than optional

Viewed 2405

Looking at the proto3 reference:

https://developers.google.com/protocol-buffers/docs/proto3#simple

It says this about singular:

singular: a well-formed message can have zero or one of this field (but not more than one).

It's not clear to me how this is different than optional. Is singular just an explicit way of stating that something is optional (which is now implicit for proto3)? Or is there something else this does that I'm missing?

Thanks.

1 Answers

Optional is proto2 syntax. Singular is proto3 syntax.

In proto3, singular is the default rule. As today the documentation needs to be improved, and there's an open issue: google/protobuf#3457.

See also google/protobuf#2497 why messge type remove 'required,optional'?, and also haberman's comment on GoogleCloudPlatform/google-cloud-python#1402:

I think the question is: what are you trying to do? Why is it relevant to you whether a field is set or not and what do you intend to do with this information?

In proto3, field presence for scalar fields simply doesn't exist. Your mental model for proto3 should be that it's a C++ or Go struct. For integers and strings, there is no such thing as being set or not, it always has a value. For submessages, it's a pointer to the submessage instance which can be NULL, that's why you can test presence for it.

Related