在运行时无法识别Proto3设置值等于默认值 [英] Proto3 setting value equal to default is not recognised in runtime

查看:217
本文介绍了在运行时无法识别Proto3设置值等于默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Proto3 不如 Proto2 那么严格,且不需要 可选字段,没有自定义默认值。

Proto3 is not as strict as Proto2, and there are no required or optional fields, there are no custom default values.

鉴于以下定义......

Given the following definition...

message Order {
    enum Side {
        BID = 0;
        ASK = 1;
    }

    int64 time = 1;
    double price = 2;
    double volume = 3;
    Side side = 4;
}

任何这些字段都有默认值,毕竟现在还没有你必须或不得提供的规则 .build()你的对象。

There are default values for any of those fields, after all now there are no rules of what you must or must not provide before you .build() your object.

所以默认为时间 0 价格 0.0 side BID ,如果您打印的是未提供的实例其中一个字段或提供默认值然后运行时会将其视为在两种情况下从未提供过,因此无法确定该值是否已手动设置为 BID 或者它被视为默认值。

So the default for time is 0, price is 0.0 and side is BID, if you print an instance where you did not provide one of the fields or provided the default value then runtime will treat it as it was never provided in both cases, so its not possible to determine if the value was manually set to BID or it was taken as the default.

例如,如果我们执行以下代码(其kotlin)

For example if we execute the following code (its kotlin)

Order.newBuilder()
        .setPrice(1.0)
        .setVolume(2.0)
        .setSide(Order.Side.BID)
        .build()
        .apply { println(this) }

我们将有这个输出

price: 1.0
volume: 2.0

至少这很烦人,因为当您使用标准 .toString()或json打印机打印原型对象时,您将拥有这个裁剪的输出...

at the very least this is annoying as when you print your proto objects using standard .toString() or json printer you'll have this cropped output...

{ "price": 1.0, "volume": 2.0 }
{ "price": 1.0, "volume": 2.0, "side": "ASK" }
{ "price": 1.0, "volume": 2.0 }
{ "price": 1.0, "volume": 2.0, "side": "ASK" }

但是,如果您的客户不一定关心违约,该怎么办?值并期望所有字段都存在?

But what if your client does not necessarily care about default values and expects all fields to be present?

问题:有没有办法改变这种行为?至少我们如何确保如果设置了价值?

也许有办法告诉 protoc 生成不同的代码(影响默认行为)...

Maybe there is a way to tell protoc to generate different code (affecting defaults behaviour)...

推荐答案

如果你想要Proto2的默认值值和设置/取消设置行为,你应该切换回Proto2。 Proto2不太可能很快就会消失,因为许多代码(包括Google内部)仍然依赖于它,并且它与Proto3共享其大部分实现。将proto2与proto3视为一种选择(实际上是您正在寻找的确切选项),而不是版本更改。

If you want Proto2's default value and set/unset behavior, you should switch back to Proto2. It is unlikely that Proto2 will go away any time soon as lots of code (including inside of Google) still depends on it, and it shares most of its implementation with Proto3. Think of proto2 vs. proto3 as an option (the exact option you're looking for, in fact) rather than a version change.

这篇关于在运行时无法识别Proto3设置值等于默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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