我们如何将变体消息(几种消息类型之一)放入 protobuf 消息中? [英] How can we put a variant message ( one of a few message types ) inside a protobuf message?
问题描述
我们如何将变体消息(几种消息类型之一)放入 protobuf 消息中?
How can we put a variant message ( one of a few message types ) inside a protobuf message?
message typeA {
....
}
message typeB {
....
}
message typeC {
[typeB|typeA] payload;
}
推荐答案
你需要这样做:
message TypeC {
optional TypeA a = 1;
optional TypeB b = 2;
}
如果有很多变体,您可能还想添加一个标签字段,这样您就不必为每个变体都检查has_*()
.
If there are a lot of variants, you might also want to add a tag field so that you don't have to check has_*()
for each one.
这在 Protobuf 文档中有介绍:https://developers.google.com/protocol-buffers/docs/techniques#union
This is covered in the Protobuf docs: https://developers.google.com/protocol-buffers/docs/techniques#union
附注.Protobufs 的这个缺失功能在 Cap'n Proto 中得到修复,这是同一作者(我)的一个新序列化系统:Cap'n Proto 为此目的实现了 "unions".在离开 Google 之前,我也在 Protobufs 中实现了联合,但是在我离开之前没有设法将我的更改合并到主线中.对不起.:(
PS. This missing feature of Protobufs is fixed in Cap'n Proto, a new serialization system by the same author (me): Cap'n Proto implements "unions" for this purpose. I had also implemented unions in Protobufs before leaving Google, but didn't manage to get my change merged into mainline before I left. Sorry. :(
看起来 Protobuf 团队最终合并了我的更改并发布了 2.6.0 版.:) 请参阅oneof
声明.
It looks like the Protobuf team eventually merged my change and released version 2.6.0 with it. :) See the oneof
declaration.
这篇关于我们如何将变体消息(几种消息类型之一)放入 protobuf 消息中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!