Starting from version 3.15 protobuf 3 officially reintroduced the optional keyword, which allows presence tracking for fields. Since presence tracking has already been available for message (non-scalar) fields, does adding optional make any difference for such fields?
Specifically, is there any difference (e.g., in terms of generated code) between
message Message {
OtherMessage field = 1;
}
and
message Message {
optional OtherMessage field = 1;
}
where OtherMessage is some defined protobuf message type.
No, it makes no difference at all. All message-typed fields already support presence.
(It's possible that the presence of the keyword is detectable via the descriptor, but I wouldn't rely on it.)
I would personally recommend against specifying optional for message-typed fields, as it gives the impression that it's a meaningful thing to do, when it's not.
Yes, it can make a difference with some libraries.
Internally protoc will make a oneof out of the optional submessage field, just like it does with optional regular fields in proto3 syntax. Libraries that support proto3 optional fields will typically convert this back to regular submessage field, as they should have presence detection in any case.
However, old protobuf libraries (older than 2020) used with new protoc versions (3.15 and newer) can expose the automatically generated oneof. For example nanopb 0.3.x series does generate an unnecessary oneof when optional is specified for a submessage, while nanopb 0.4.x recognizes it as optional field.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With