Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does optional have any meaning for fields of message types in protobuf 3?

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.

like image 451
Alex Che Avatar asked Oct 16 '25 19:10

Alex Che


2 Answers

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.

like image 156
Jon Skeet Avatar answered Oct 18 '25 08:10

Jon Skeet


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.

like image 31
jpa Avatar answered Oct 18 '25 10:10

jpa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!