介绍一下消息的不一样类型和引用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;
...
}复制代码