我应该使用 Get 方法获取值还是应该直接使用字段?

Should I use Get methods to get values or should I use fields directly?

我第一次在 Go 中使用 protobuf(和 protoc)。

message MyProtoStruct {
  string description = 1;
}

我有点困惑:

  1. 我应该使用方法来获取值(如 MyProtoStruct.GetDescription())还是

  2. 我应该直接使用字段吗(比如MyProtoStruct.Description)?

你可以使用任何一个。请注意,对于 proto2 生成的代码而不是 proto3(proto2 是默认值),协议缓冲区消息中的字段始终是指针。在这种情况下,如果字段为 nil,则吸气剂 return 为零值。这非常方便,因为很难编写直接使用字段的代码,而不会在字段丢失时导致 nil 指针取消引用。

proto3 生成的代码中(我建议您使用,原因不止一个),我建议您直接使用字段。在 proto2 生成的代码中,我建议使用 get 方法。