Protocol Buffer 可选整数,不同于零 [英] Protocol Buffer optional integer, distinct from zero

查看:63
本文介绍了Protocol Buffer 可选整数,不同于零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在协议缓冲区版本 3 中,我试图找出具有可选整数值的最佳方法,其中零和不存在应该是不同的情况.我能想到的最好的方法是制作一种类型:

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?

推荐答案

在 proto3 中有两个主要选项.第一种是使用你建议的 oneof ,但实际上你只需要在 oneof 中有一个项目:

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 字段具有存在的概念,因此您仍然可以确定 value 是不存在还是为零.另一种选择是使用 中的一种包装器类型google/protobuf/wrappers.proto.这些包装器中的每一个都只采用一个原始类型并将其包装在消息中,这对您的情况有所帮助,因为子消息字段存在.例如,Int64 包装器如下所示:

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;
}

最后,要考虑的另一件事是您始终可以继续使用 proto2.protobuf 3.0 及更高版本均支持 proto2 和 proto3 样式,我们计划无限期地继续支持 proto2.

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.

这篇关于Protocol Buffer 可选整数,不同于零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆