I need to specify a message with an optional field in protobuf (proto3 syntax). In terms of proto 2 syntax, the message I want to express is something like:
Since protobuf release 3.12, proto3 has experimental support for using the optional keyword (just as in proto2) to give a scalar field presence information.
syntax = "proto3";
message Foo {
int32 bar = 1;
optional int32 baz = 2;
}
A has_baz()/hasBaz() method is generated for the optional field above, just as it was in proto2.
Under the hood, protoc effectively treats an optional field as if it were declared using a oneof wrapper, as CyberSnoopy’s answer suggests:
message Foo {
int32 bar = 1;
oneof optional_baz {
int32 baz = 2;
}
}
If you’ve already used that approach, you'll be able to clean up your message declarations (switch from oneof to optional) once proto3 optional support graduates from experimental status, since the wire format is the same.
You can find the nitty-gritty details about field presence and optional in proto3 in the Application note: Field presence doc.
Pass the --experimental_allow_proto3_optional flag to protoc to use this functionality in release 3.12. The feature announcement says it will be “generally available hopefully in 3.13”.
Nov 2020 Update: The feature is still considered experimental (flag required) in release 3.14. There are signs of progress being made.