From the protobuf wire format we can tell whether a specific field exists or not. And in protobuf 2 generated code, all fields have a "HasXXX" method to tell whether the field exists or not in code. However in proto 3, we lost that ability. E.g. now we can't tell if a int32 field is missing, or has a value of 0 (default for int32 type).
In many scenario, we need the ability to differentiate missing vs default value (basically nullable support for scalar types).
Feng suggest workarounds:
- Use a wrapper message, such as google.protobuf.Int32Value. In proto3, message fields still have has-bits.
- Use an oneof. For example:
message Test1 {
oneof a_oneof {
int32 a = 1;
}
}
then you can check test.getAOneofCase().
However, this requires change the message definition, which is a no go if you need to keep the message compatible while upgrade from proto2 to proto 3.
Read full article from Missing value/null support for scalar value types in proto 3 · Issue #1606 · protocolbuffers/protobuf · GitHub
No comments:
Post a Comment