What's the preferred way to encode a “nullable” field in protobuf 2?

前端 未结 2 1561
醉梦人生
醉梦人生 2021-02-06 01:27

I am defining a ProtoBuf message where I want to have a \"nullable\" field -- i.e., I want to distinguish between the field having a value and not having a value. As a concrete

相关标签:
2条回答
  • 2021-02-06 02:10

    Protobuf 2 messages have a built-in notion of "nullable fields". The C++ interface contains methods has_xxx and clear_xxx to check if the field has been set and to unset the field, respectively.

    This feature comes "for free" due to the way fields are encoded in message using "tags". An unset field is simply "not present" in the encoded message.

    Proto 3 does not have this feature, instead setting any missing field to its default value.

    0 讨论(0)
  • 2021-02-06 02:10

    Have a notion of NaN for each of the types and then use default (as shown below) to set it as the value. This will be used if nothing is specified for that particular field.

    optional float x = 1 [default = -1];
    
    0 讨论(0)
提交回复
热议问题