How can we put a variant message ( one of a few message types ) inside a protobuf message?

你。 提交于 2019-12-29 06:48:14

问题


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

回答1:


You need to do it like this:

message TypeC {
  optional TypeA a = 1;
  optional TypeB b = 2;
}

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.

This is covered in the Protobuf docs: https://developers.google.com/protocol-buffers/docs/techniques#union

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. :(

EDIT: It looks like the Protobuf team eventually merged my change and released version 2.6.0 with it. :) See the oneof declaration.




回答2:


Check out the new oneof feature in version 2.6: https://developers.google.com/protocol-buffers/docs/reference/java-generated#oneof

You can now do something like this:

message TypeC {
    oneof oneof_name {
        TypeA a = 1;
        TypeB b = 2;
    }
}

Fields in the same oneof will share memory and only one field can be set at the same time.



来源:https://stackoverflow.com/questions/20970836/how-can-we-put-a-variant-message-one-of-a-few-message-types-inside-a-protobu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!