golang / protobuf

Go support for Google's protocol buffers
BSD 3-Clause "New" or "Revised" License
9.72k stars 1.58k forks source link

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

Closed frederikhors closed 3 years ago

frederikhors commented 3 years ago

I'm using this project 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)?

puellanivis commented 3 years ago

The usual recommendation is to use the GetDescription() if the containing struct might be nil (i.e. the Message does not appear on the wire) so typically when there is a sub-Message. So, MyWrappingProtoStruct.MyProtoStruct.GetDescription() should always produce a value, and not panic, if MyWrappingProtoSctruct.MyProtoStruct == nil, meanwhile MyWrappingProtoStruct.MyProtoStruct.Description would panic under the same conditions.

If you’re just accessing flat fields of a protobuffer struct, then you can go ahead and access the values directly… that’s what the GetField() function will be doing anyways, if the compiler can guarantee that the containing struct is definitely not nil. (i.e. myPB := new(MyProtoStruct); fmt.Println(myPB.GetDescription(), myPB.Description) both compile into essentially the same code, because the compiler knows that myPB cannot be nil so it shortcircuits the nil guard check, and doesn’t need to generate it.)

frederikhors commented 3 years ago

@puellanivis Thank you very much!