How can we put a message variant (one of several message types) in a protobuf message?

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

message typeA { .... } message typeB { .... } message typeC { [typeB|typeA] payload; } 
+7
protocol-buffers
source share
2 answers

You need to do it like this:

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

If there are many options, you can also add a tag field so that you do not need to check has_*() for each of them.

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

PS. This missing Protobufs feature has been fixed in Cap'n Proto , a new serialization system of the same author (me): Cap'n Proto implements "union" for this purpose. I also implemented unions at Protobufs before leaving Google, but before I left, I was not able to merge my changes into the backbone. Sorry .: (

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

+20
source share

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

Now you can do something like this:

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

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

+13
source share

All Articles