Protocol Buffer optional integer, distinct from ze

2019-04-15 14:08发布

问题:

In Protocol Buffer version 3, I'm trying to figure out the best way to have a optional integer value, where zero and absent should be distinct cases. Best I can figure is making a type:

message int64Option {
    oneof option {
        bool empty = 14;
        int64 value = 15;
    }
}

Is this a good idea, or is there a better way?

回答1:

There are two main options for this in proto3. The first is to use a oneof like you suggested, but actually you only need to have one item in the oneof:

oneof option {
  int64 value = 15;
}

Oneof fields have a notion of presence so you can still determine whether value is absent or zero. The other alternative is to use one of the wrapper types in google/protobuf/wrappers.proto. Each of these wrappers just takes a primitive type and wraps it in a message, and this helps in your situation because submessage fields have presence. Here is what the Int64 wrapper looks like for example:

// Wrapper message for `int64`.
//
// The JSON representation for `Int64Value` is JSON string.
message Int64Value {
  // The int64 value.
  int64 value = 1;
}

Finally, one other thing to consider is that you can always keep using proto2. Both the proto2 and proto3 styles are supported in protobuf versions 3.0 and up and we plan to continue supporting proto2 indefinitely.