如何在protobuf 3中定义一个可选字段 [英] How to define an optional field in protobuf 3

查看:68
本文介绍了如何在protobuf 3中定义一个可选字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 protobuf(proto3 语法)中指定一个带有可选字段的消息.在proto 2语法方面,我想表达的信息是这样的:

message Foo {所需的 int32 bar = 1;可选的 int32 baz = 2;}

根据我的理解,可选"概念已从语法原型 3 中删除(连同必需的概念).尽管尚不清楚替代方案 - 使用默认值声明尚未从发送方指定字段,如果默认值属于有效值域(例如考虑布尔类型),则会留下歧义.

那么,我应该如何对上面的消息进行编码?谢谢.

解决方案

自从 protobuf 版本 3.15,proto3 支持使用 optional 关键字(就像在 proto2 中一样)来提供标量字段存在信息.

syntax = proto3";消息 Foo {int32 酒吧 = 1;可选的 int32 baz = 2;}

一个 has_baz()/hasBaz() 方法是为上面的 optional 字段生成的,就像在 proto2 中一样.>

在幕后,protoc 有效地将 optional 字段视为使用 oneof 包装器声明,如 Cyber​​Snoopy 的回答 建议:

message Foo {int32 酒吧 = 1;oneof optional_baz {int32 baz = 2;}}

如果您已经使用过这种方法,现在可以简化您的消息声明(从 oneof 切换到 optional)和代码,因为有线格式是相同的.

有关 proto3 中的字段存在和 optional 的基本细节可以在 应用说明:现场存在 doc.

历史说明:proto3 中对 optional 的实验性支持于 2020 年 4 月 23 日在 此评论.使用它需要在 3.12-3.14 版本中向 protoc 传递 --experimental_allow_proto3_optional 标志.

I need to specify a message with an optional field in protobuf (proto3 syntax). In terms of proto 2 syntax, the message I want to express is something like:

message Foo {
    required int32 bar = 1;
    optional int32 baz = 2;
}

From my understanding "optional" concept has been removed from syntax proto 3 (along with required concept). Though it is not clear the alternative - using the default value to state that a field has not been specified from the sender, leaves an ambiguity if the default value belongs to the valid values domain (consider for example a boolean type).

So, how am I supposed to encode the message above? Thank you.

解决方案

Since protobuf release 3.15, proto3 supports using the optional keyword (just as in proto2) to give a scalar field presence information.

syntax = "proto3";

message Foo {
    int32 bar = 1;
    optional int32 baz = 2;
}

A has_baz()/hasBaz() method is generated for the optional field above, just as it was in proto2.

Under the hood, protoc effectively treats an optional field as if it were declared using a oneof wrapper, as CyberSnoopy’s answer suggested:

message Foo {
    int32 bar = 1;
    oneof optional_baz {
        int32 baz = 2;
    }
}

If you’ve already used that approach, you can now simplify your message declarations (switch from oneof to optional) and code, since the wire format is the same.

The nitty-gritty details about field presence and optional in proto3 can be found in the Application note: Field presence doc.

Historical note: Experimental support for optional in proto3 was first announced on Apr 23, 2020 in this comment. Using it required passing protoc the --experimental_allow_proto3_optional flag in releases 3.12-3.14.

这篇关于如何在protobuf 3中定义一个可选字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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