Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
787 views
in Technique[技术] by (71.8m points)

go - How to update nested protobuf field

I'm using protobuf 3.14 in Go, trying to update some nested field, but it causes panic:

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x30 pc=0x670028]

The .proto file:

syntax = "proto3";
option go_package = ".;my";

message My {
    message _struct {
        bytes Data = 1;
    }

    _struct Struct = 2; // e
}

The go code:

package main

import (
    "aj/my"
)

func main() {
    m := my.My{}
    m.Struct.Data = []byte{1, 2, 3} // this causes panic, how to set it correctly?
}

I need to modify the value, but I don't see any setter in .pb.go, how to modify it ?

question from:https://stackoverflow.com/questions/66068618/how-to-update-nested-protobuf-field

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is that m.Struct is just a pointer to _struct type and it's not initialized yet, so you can't assign anything to it's Data Field.

If you look at the generated code for My message, it's something like this:

type My struct {
    state         protoimpl.MessageState
    sizeCache     protoimpl.SizeCache
    unknownFields protoimpl.UnknownFields

    Struct *My_XStruct
}

so Struct type is pointer to My_XStruct. You have to do something like this:

m := my.My{}
m.Struct = &my.My_XStruct{}
m.Struct.Data = []byte{1, 2}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...