Protobuf(二)proto3语法格式

.proto文件有两种语法标准:proto2和proto3,我们以proto3为例,其语法格式如下:

message   {
      =  
       规则          类型          名称           编号  
}
  • message_name: 同一个pkg内,必须唯一
  • filed_rule: 可以没有, 常用的有repeated, oneof
  • filed_type: 数据类型, protobuf定义的数据类型, 生产代码的会映射成对应语言的数据类型
  • filed_name: 字段名称, 同一个message 内必须唯一
  • field_number: 字段的编号, 序列化成二进制数据时的字段编号

2.1.1、字段规则
 

2.1.2、字段类型

基础类型

参考官方文档(Language Guide (proto3)  |  Protocol Buffers  |  Google Developers),我这里只保留了我常用编程语言的字段类型

.proto Type Notes C++ Type Python Type[3] C# Type
double double float double
float float float float
int32 Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint32 instead. int32 int int
int64 Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint64 instead. int64 int/long[4] long
uint32 Uses variable-length encoding. uint32 int/long[4] uint
uint64 Uses variable-length encoding. uint64 int/long[4] ulong
sint32 Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int32s. int32 int int
sint64 Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int64s. int64 int/long[4] long
fixed32 Always four bytes. More efficient than uint32 if values are often greater than 228. uint32 int/long[4] uint
fixed64 Always eight bytes. More efficient than uint64 if values are often greater than 256. uint64 int/long[4] ulong
sfixed32 Always four bytes. int32 int int
sfixed64 Always eight bytes. int64 int/long[4] long
bool bool bool bool
string A string must always contain UTF-8 encoded or 7-bit ASCII text, and cannot be longer than 232. string str/unicode[5] string
bytes May contain any arbitrary sequence of bytes no longer than 232. string str (Python 2)
bytes (Python 3)
ByteString

枚举类型

语法如下:

enum  {
     = 
}
  • enum_name: 枚举名称
  • element_name: pkg内全局唯一, 很重要
  • element_number: 必须从0开始, 0表示类型的默认值, 32-bit integer

如下示例,Corpus就是我们定义的一个枚举类型。

message SearchRequest {
  string query = 1;
  int32 page_number = 2;
  int32 result_per_page = 3;
  enum Corpus {
    UNIVERSAL = 0;
    WEB = 1;
    IMAGES = 2;
    LOCAL = 3;
    NEWS = 4;
    PRODUCTS = 5;
    VIDEO = 6;
  }
  Corpus corpus = 4;
}

如果需要将不同的枚举常量映射到相同的值。将allow_alias选项设置为true即可。(最好不要这么使用)

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

2.1.3、字段编号
 

2.1.4、综合示例

你可能感兴趣的:(Protobuf,proto3)