Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

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

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...