Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proto3 Nested Message Getter is not useful #54

Closed
mwitkow opened this issue Jul 27, 2015 · 4 comments
Closed

Proto3 Nested Message Getter is not useful #54

mwitkow opened this issue Jul 27, 2015 · 4 comments

Comments

@mwitkow
Copy link

mwitkow commented Jul 27, 2015

Take this generated code:

type FlagId struct {
    Deployment *DeploymentId `protobuf:"bytes,1,opt,name=deployment" json:"deployment,omitempty"`
    Name       string        `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"`
}

func (m *FlagId) Reset()         { *m = FlagId{} }
func (m *FlagId) String() string { return proto.CompactTextString(m) }
func (*FlagId) ProtoMessage()    {}

func (m *FlagId) GetDeployment() *DeploymentId {
    if m != nil {
        return m.Deployment
    }
    return nil
}

What is the purpose of this Getter? It will not be called on a nil m *FlagId.
I actually hoped it would create an new instance of the type behind the Deployment field, but it seems to not do anything other than a normal m.Deployment would.

I really hoped it would create a new instance if it was nil, this way I could solve the problem in without reflection:
grpc-ecosystem/grpc-gateway#32

@dsymonds
Copy link
Contributor

The point is so that deeply nested proto types (e.g. message field in a message that's a field of another message, etc.) can be traversed simply, and without regard for nil message pointers along the way. You can write m.GetFoo().GetBar().GetBaz() and only check for nil right at the end.

If you don't find it useful, don't use it.

@mwitkow
Copy link
Author

mwitkow commented Jul 28, 2015

Oh, didn't know you could do m.GetFoo().GetBar().GetBaz().

That's pretty cool. However, it doesn't strike me as immediately obvious. Is there a place where such things are documented? Like golang/protobuf Tips&Tricks? ;)

@dsymonds
Copy link
Contributor

It's mentioned in the README and in the package doc, perhaps not so explicitly.

@omanamos
Copy link

omanamos commented Jun 8, 2016

Is there a reason why the getters don't follow a similar pattern to the C++ API, which allows you to call mutable_field() and creates an object if it doesn't already exist.

Otherwise I end up writing a block like this every time I access a sub message field:

if msg.Field == nil {
  msg.Field = &pb.FieldMsg{}
}

@golang golang locked and limited conversation to collaborators Jun 26, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants