proto2与proto3的基本语法

1)注释 //

2)选择哪个版本协议
syntax = "proto2"
或
syntax = "proto3"

3)定义一个协议类型,先从2讲起
syntax = "proto2"
message my_person { // 消息开始
	required string name = 1;
	required int32 age = 2;
	optional int32 sex = 3;
	repeated uint32 array_value = 4;
} // 消息结束

4)每一行
// 字段规则(required) 字段类型(int32) 字段名字(age) 字段标识号(1)

5)规则
required: 该值必须设置
optional: 可以不设置,不设置则不会编码进去; 解码后是默认值
repeated: 字段可以重复任意多次(包括0次),类似于List、vector数组

6)数据类型
double
float
int32
sint32: 编码为负数时,比int32高效
int 64
sint64
fixed32:
fixed64:
sfixed32:
sfixed64:
bool: utf-8 或 7-bit ascii
string:
bytes:

7)每次定义完一个数据成员,以分号结尾

8)枚举
enum Direction {
	START = 0;
	EAST = 1;
	SOUTH = 2;
	WEST = 3;
	NORTH = 4;
};

9)包: 防止不同消息类型,存在命名冲突。 c/c++是名字空间
package test;

10)message的嵌套使用
message address_book {
	repeated myperson persons = 1; // 人物联系表
}

11)proto3与proto2的区别
  (1)移除required
      λ protoc.exe --cpp_out=./ test3.proto
	  test3.proto:16:18: Explicit 'optional' labels are disallowed in the Proto3 syntax. To define 'optional' fields in Proto3, simply remove the 'optional' label, as fields are 'optional' by default.
  (2)optional改为singular(也去掉)
  (3)移除了default选项。proto3中,字段的默认值只能根据字段类型由系统决定
  (4)枚举类型的第一个字段必须为0
      λ protoc.exe --cpp_out=./ test3.proto
	  test3.proto: The first enum value must be zero in proto3.

12)proto2
syntax = "proto2";
package test;

enum Direction {
	START = 0;
	EAST = 1;
	SOUTH = 2;
	WEST = 3;
	NORTH = 4;
};

message myperson { // 消息开始
	required string name = 1;
	required int32 age = 2;
	optional int32 sex = 3;
	repeated uint32 array_value = 4;
} // 消息结束

message address_book {
	repeated myperson persons = 1; // 人物联系表
}

13)proto3
syntax = "proto3";
package test;
enum Direction {
	EAST = 1;
	SOUTH = 2;
	WEST = 3;
	NORTH = 4;
};

message myperson { // 消息开始
	string name = 1;
	int32 age = 2;
	int32 sex = 3;
	repeated uint32 array_value = 4;
} // 消息结束

message address_book {
	repeated myperson persons = 1; // 人物联系表
}

 

你可能感兴趣的:(proto2与proto3的基本语法)