2

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

blackgreen
  • 34,072
  • 23
  • 111
  • 129
Zhixin Wen
  • 95
  • 8

1 Answers1

0

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.

blackgreen
  • 34,072
  • 23
  • 111
  • 129