如何使用 protoreflect 在 Go 的 protobuf 切片字段中添加一个 nil 条目?

huangapple go评论71阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2022年1月8日 09:46:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/70629035.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定