介紹一下消息的不一樣類型和引用javascript
您可使用其餘消息類型做爲字段類型。例如,假設你想在每一個SearchResponse
消息中包含Result
消息,您能夠在同一個.proto
中定義一個Result
消息類型,而後在SearchResponse
中指定一個Result
類型的字段:java
message SearchResponse {
repeated Result results = 1;
}
message Result {
string url = 1;
string title = 2;
repeated string snippets = 3;
}複製代碼
在上述示例中,Result
消息類型與SearchResponse
在相同的文件中定義, 若是要使用的消息類型已經在另外一個.proto
文件中定義了怎麼解決呢?編程
你能夠經過import
引入其餘的.proto
文件:編程語言
import "myproject/other_protos.proto";複製代碼
注意ui
接上邊的例子,假如a.proto
引入了b.proto
,可是b.proto
更換了位置,路徑變成了test/b.proto
(隨便舉例),咱們有兩種解決辦法:google
a.proto
中的import
語句,直接import "test/b.proto"
b.proto
文件原來的位置,建立一個b.proto
文件,文件內容爲import public "test/b.proto"
,就能夠了
import
對proto2
和proto3
都適用編碼
您能夠在其餘消息類型中定義和使用消息類型,以下,Result
消息定義在SearchResponse
消息中:url
message SearchResponse {
message Result {
string url = 1;
string title = 2;
repeated string snippets = 3;
}
repeated Result results = 1;
}複製代碼
若是想重複使用Result
,能夠用Parent.Type
的方式使用:spa
message AnotherResponse {
SearchResponse.Result res = 1;
}複製代碼
修改時要注意的規則:code
reserved
裏Any
類型any類型時谷歌protobuf內置的一個類型,通用類型,使用的時候須要導入google/protbuf/any.proto
import "google/protobuf/any.proto";
message ErrorStatus {
string message = 1;
repeated google.protobuf.Any details = 2;
}複製代碼
Oneof
類型Oneof結構中有多個字段,可是同一時刻只有一個字段生效
message SampleMessage {
oneof test_oneof {
string name = 4;
SubMessage sub_message = 9;
}
}複製代碼
oneof中能夠是任意類型,除了repeated 字段
生成代碼以後,也會對oneof字段生成getter,setter方法,可是出來的值須要你本身判斷一下
若是你要定義一個map,protobuf提供了一個語法:
map<key_type, value_type> map_field = N;複製代碼
例如
map<string, Project> projects = 3;複製代碼
注意事項
repeated
.proto
文件生成時,map按key排序你能夠添加一個可選標識package
到.proto
文件中。用來防止命名衝突
package foo.bar;
message Open { ... }複製代碼
在使用這條消息的時候須要加上package
名字
message Foo {
...
foo.bar.Open open = 1;
...
}複製代碼