博客 / 詳情

返回

protobuf 使用其他消息類型message的三種方式

更方便的在微信公眾號閲讀文章可以關注公眾號:海生的go花園
圖片

在我們寫protobuf最基礎的是有 基本的數字,字符串,枚舉類型組成,在這些基礎的類型基礎上,我們組合成一個message類型。
接下來我們探討一下,如何在message裏面再使用其他的message類型。

方式一:使用其他消息類型作為字段類型

您可以使用其他消息類型作為字段類型。
例如,我們想在SearchResponse使用Result類型。
此時我們可以先在同一個.proto文件中定義一個Result消息類型,然後在SearchResponse這個消息類型中當做自己的一個 字段 使用如下。

message SearchResponse {
  repeated Result results = 1;
}

message Result {
  string url = 1;
  string title = 2;
  repeated string snippets = 3;
}

方式二:導入其他文件的方式

在上面的例子中,Result和SearchResponse消息類型在同一個文件中定義。
如果我們想用作字段類型的消息類型Result已經在另一個.proto文件中定義了怎麼辦?
可以通過導入其他.proto文件來使用它們的定義。
要導入另一個的定義,您可以在文件頂部添加一個導入語句:.proto

import "myproject/other_protos.proto";

比如在 a.proto的文件中有Result
我們那麼引入使用

import "myproject/a.proto";

方式三:嵌套類型

message SearchResponse {
  message Result {
    string url = 1;
    string title = 2;
    repeated string snippets = 3;
  }
  repeated Result results = 1;
}

如果要在其父消息類型之外重用此消息類型,請將其稱為_Parent_._Type_:

message SomeOtherMessage {
  SearchResponse.Result result = 1;
}
user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.