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

1

8

I'm using protobuf (and protoc) for the first time with Go.

message MyProtoStruct {
  string description = 1;
}

I'm a little bit confused:

  1. should I use methods to get values (like MyProtoStruct.GetDescription()) or

  2. should I use fields directly (like MyProtoStruct.Description)?

Mall answered 3/7, 2021 at 11:29 Comment(1)
I woudl go for 1.Ferocity
L
9

You can use either. Note that for proto2 generated code rather than proto3 (proto2 is the default), fields in protocol buffer messages are always pointers. In that case, the getters return a zero value if the field is nil. That's very convenient, since it's quite difficult to write code that uses fields directly without causing nil pointer dereferences when a field is missing.

In proto3 generated code (which I'd suggest you use, for more than one reason), I'd suggest you use fields directly. In proto2 generated code, I'd suggest using the get methods.

Livelihood answered 3/7, 2021 at 11:44 Comment(3)
What are the advantages of using fields directly in proto3?Crossruff
It would be nice to see this answer in the official documentation and/or to see the reasoning of why direct field access is preferred over using a getter in proto3. Because it's hard to argue that a getter shouldn't be used (in a collaborative environment) without reasons why. Secondly, there is the question of why are getters added in proto3 if they're not recommended for use? Is it because of backwards compatibility or something else?Trawl
@TobyArtisan "Use the struct’s fields when you can, but you’ll find the getters useful when you have multiple messages with the same getter(s) and you want to abstract those method(s) into an interface." This is from the book "Distributed services with Go".Agra

© 2022 - 2025 — McMap. All rights reserved.