英文:
How to add a nil entry in Go protobuf slice field with protoreflect?
问题
我的生成的Protobuf Go结构如下所示:
type ProtoStruct struct {
A []*SomeStruct
}
我现在正在尝试使用protoreflect向该切片追加一个nil条目。
我尝试了以下代码:
var v protoreflect.Value // 从之前的步骤中获取这个值
v.List().Append(protoreflect.ValueOf(nil))
但是它会引发错误:
类型不匹配:无法将nil转换为消息类型
英文:
My generated protobuf Go struct looks like:
type ProtoStruct {
A []*SomeStruct
}
I am now trying to append a nil entry to that slice with protoreflect.
I tried:
var v protoreflect.Value // somehow get this value from previous steps
v.List().Append(protoreflect.ValueOf(nil))
And it panics with:
> type mismatch: cannot convert nil to message
答案1
得分: 0
List().Append()方法的参数应该是一个protoreflect.Value,其中包含适当的类型信息。
要追加一个有类型的protobuf的nil项,你可以使用protoreflect.ValueOf方法,如下所示:
var a *pb.SomeStruct
v.List().Append(protoreflect.ValueOf(a.ProtoReflect()))
请注意,这不会导致空指针解引用的恐慌。ProtoReflect()方法调用处理了接收者为nil的情况;它将返回一个适当初始化的protoreflect.Message,其中包装了一个nil值,然后你可以成功地将其传递给ValueOf方法。
英文:
The argument to List().Append() is supposed to be a protoreflect.Value that carries appropriate type information.
To append a typed protobuf nil item, you can use protoreflect.ValueOf in this way:
var a *pb.SomeStruct
v.List().Append(protoreflect.ValueOf(a.ProtoReflect()))
Note that this will not cause a panic for nil pointer dereference. The ProtoReflect() method call deals with the receiver being nil; it will return an appropriately initialized protoreflect.Message wrapping a nil value, which you can then successfully pass into ValueOf.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论