Protocol Buffers语言简单学习

工作需求,学习一波Protocol Buffers,作为记录,官方文档:
https://developers.google.com/protocol-buffers/docs/proto3

syntax = "proto3";

message SearchRequest {
  string query = 1;
  int32 page_number = 2;
  int32 result_per_page = 3;
}

第一行
指定使用的是proto3的语法,如果不指定,默认proto2,必须非空非注释
message
定义的及结构体,message后接名称,内部定义结构体内部变量名和变量类型
field后的数字
这些字段号用于以消息二进制格式标识字段,并且在使用消息类型后不应更改。尽量将常用的字段用1~15标识,因为他们只需要一个字节,之后越往上消耗越多。
如何添加注释
1.使用//
2.使用/* */
reserved 的使用
若是你通过注释或者删除修改了一些字段,则当再次使用这些字段或者字段对应的数字的时候会出现严重问题,这时候可以使用reserved来标识这些字段名称和对应的数字

message Foo {
  reserved 2, 15, 9 to 11;
  reserved "foo", "bar";
}

这样就无法再次使用被保留的字段
repeated 的使用

message SearchResponse {
  repeated Result results = 1;
}

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

定义枚举

enum EnumAllowingAlias {
  option allow_alias = true;
  UNKNOWN = 0;
  STARTED = 1;
  RUNNING = 1;
}
enum EnumNotAllowingAlias {
  UNKNOWN = 0;
  STARTED = 1;
  // RUNNING = 1;  // Uncommenting this line will cause a compile error inside Google and a warning message outside.
}

参考文档:
https://developers.google.com/protocol-buffers/docs/proto3

发布了212 篇原创文章 · 获赞 33 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/hello_bravo_/article/details/104292288
今日推荐