How to create an object of a type *T given T is a generic type with the constraint proto.Message?

73 views Asked by At

I'm trying to implement a generic function with the signature func[T proto.Message]() in which the implementation instantiates an object of type *T. For example, the a call would look something like f[*MyProtoMessage]() (since the generated code has *MyProtoMessage implement proto.Message and MyProtoMessage does not).

Since T itself would be *MyProtoMessage, new(T) would return nil.

I've tried:

    it := reflect.Indirect(reflect.ValueOf(lo.Empty[T]()))
    t := it.Interface()

but it errors with reflect: call of reflect.Value.Interface on zero Value.

Is there a way to create an object of type *T?

1

There are 1 answers

1
Noel Yap On

lo.Empty[T]().ProtoReflect().New().Interface() creates a pointer to a non-nil instance of the underlying type, *T.