Skip to content

protoc-gen-go: generate allocating accessors for message fields #1192

Open
@chrisguiney

Description

@chrisguiney

Is your feature request related to a problem? Please describe.
My problem is that when I have a message that contains another message in a field, I have to manually check if it's been set or not and potentially allocate it myself. This results in me writing very boilerplate code to provide such an accessor method.

Describe the solution you'd like
I would like protoc-gen-go to automatically generate these accessors. Something along the lines of

func (x *Message1) GetAllocatedMessage2() *Message2 {
    if x.Message2 ==  nil {
        x.Message2 = new(Message2)
    }
    return x.Message2
}

Describe alternatives you've considered

  • hand writing these accessor methods (what i'm currently doing)
  • writing a script to generate them (maybe the next step)
  • sticking with gogo/protobuf forever
  • writing a custom generator (seems like it'd require a ton of work/essentially forking protoc-gen-go)

Additional context

  • I'm trying to migrate from gogo/protobuf, which enabled me to have messages directly embedded in the parent, where nilness wasn't ever a possibility.
  • the c++ generated code doesn't seem to have a problem allocating where necessary
  • a more terse name than GetAllocatedMessage2() would be appreciated.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions