如何更新嵌套的 protobuf 字段
How to update nested protobuf field
我在 Go 中使用 protobuf 3.14,试图更新一些嵌套字段,但它导致了恐慌:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x30 pc=0x670028]
.proto 文件:
syntax = "proto3";
option go_package = ".;my";
message My {
message _struct {
bytes Data = 1;
}
_struct Struct = 2; // e
}
go代码:
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?
}
我需要修改值,但在.pb.go[=23=中没有看到任何setter ], 如何修改?
问题是 m.Struct
只是一个指向 _struct
类型的指针,它还没有初始化,所以你不能给它的 Data
字段赋值。
如果您查看 My
消息的生成代码,它是这样的:
type My struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Struct *My_XStruct
}
所以 Struct
类型是指向 My_XStruct
的指针。你必须这样做:
m := my.My{}
m.Struct = &my.My_XStruct{}
m.Struct.Data = []byte{1, 2}
我在 Go 中使用 protobuf 3.14,试图更新一些嵌套字段,但它导致了恐慌:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x30 pc=0x670028]
.proto 文件:
syntax = "proto3";
option go_package = ".;my";
message My {
message _struct {
bytes Data = 1;
}
_struct Struct = 2; // e
}
go代码:
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?
}
我需要修改值,但在.pb.go[=23=中没有看到任何setter ], 如何修改?
问题是 m.Struct
只是一个指向 _struct
类型的指针,它还没有初始化,所以你不能给它的 Data
字段赋值。
如果您查看 My
消息的生成代码,它是这样的:
type My struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Struct *My_XStruct
}
所以 Struct
类型是指向 My_XStruct
的指针。你必须这样做:
m := my.My{}
m.Struct = &my.My_XStruct{}
m.Struct.Data = []byte{1, 2}