Protobuf 重复消息选项

Ves*_*niK 5 protocol-buffers

我试图通过扩展 google.protobuf.MessageOptions 将一些文档元信息附加到 protobuf 消息。我的元信息选项之一可能会出现不止一次。看起来我可以声明重复选项,但如何在消息中使用它?

这是我尝试实现的目标的示例:

extend google.protobuf.MessageOptions {
    optional string description = 51234;
    repeated string usages = 51235;
}

message MyMsg {
    option (description) = "MyMsg description";
    option (usages) = ???

    optional bool myFlag = 1;
    optional string myStr = 2;
}
Run Code Online (Sandbox Code Playgroud)

我应该输入什么而不是???如果我想记录两种不同的使用方式?

Ken*_*rda 5

如果我没记错的话,您可以多次指定重复选项:

message MyMsg {
  option (description) = "MyMsg description";
  option (usages) = "usage1";
  option (usages) = "usage2";

  optional bool myFlag = 1;
  optional string myStr = 2;
}
Run Code Online (Sandbox Code Playgroud)

编辑:没有记录访问重复字段的方式,并且花了一些时间来查看标题,所以我决定将它添加到这个答案中:

auto opts = MyMsg::descriptor()->options();
std::cout << opts.GetExtension(description) << std::endl;
for (int i = 0; i < opts.ExtensionSize(usages); ++i)
    std::cout << opts.GetExtension(usages, i) << std::endl;
Run Code Online (Sandbox Code Playgroud)

  • @GillBates 根据文档 [here](https://developers.google.com/protocol-buffers/docs/proto#customoptions),其语法是: message Bar { optional int32 a = 1 [(foo_options).opt1 = 123, (foo_options).opt2 = "baz"]; // 替代聚合语法(使用 TextFormat):可选 int32 b = 2 [(foo_options) = { opt1: 123 opt2: "baz" }]; } (2认同)