如何在协议缓冲区中提供默认值?

how to give default values in protocol buffer?

message Person {
  required Empid = 1 [default = 100];
  required string name = 2 [default = "Raju"];
  optional string occupation = 3;
  repeated string snippets = 4;
}

我可以给上面提到的默认值吗?

更新:以下答案仅适用于 proto2,proto3 不允许自定义默认值。

是的,您可以按照您写的那样提供默认值。 default 对于 required 是可选的,但对于 optional 您必须提及 default 值,否则会自动分配特定类型的值。此外,您忘记提及 Empid.

的类型

protobuf 语言指南指出

If the default value is not specified for an optional element, a type-specific default value is used instead: for strings, the default value is the empty string. For bools, the default value is false. For numeric types, the default value is zero. For enums, the default value is the first value listed in the enum's type definition. This means care must be taken when adding a value to the beginning of an enum value list.

对于 proto3,不允许自定义默认值。