In proto3, all fields are "optional" (if the sender cannot specify them). But the fields are no longer βnullableβ since there is no way to tell the difference between a field that has a default value explicitly set and one that has not been set at all.
If you need the "null" state (and there is no value out of range that you can use for this), you will need to encode this as a separate field instead. For example, you can do:
message Foo { bool has_baz = 1; // always set this to "true" when using baz int32 baz = 2; }
Alternatively, you can use oneof :
message Foo { oneof baz { bool baz_null = 1; // always set this to "true" when null int32 baz_value = 2; } }
The oneof version is more explicit and more efficient on the web, but requires an understanding of how oneof values oneof .
Finally, another perfectly reasonable option is to stick with proto2. Proto2 is not outdated, and in fact, many projects (including those inside Google) are very dependent on proto2 functions that are removed in proto3, so they probably will never switch. Thus, it is safe to use it for the foreseeable future.
source share