我试图使用泛型将JSON对象转换为具有枚举的GRPC响应,即:
type GRPCResponse {
str string
enu EnumType
}
type EnumType int32
const (
Type1 EnumType = 0
Type2 EnumType = 1
)解编组功能如下所示:
func assertHTTPResponseOK[T any](t *testing.T, endpoint string) T {
body, err := GetResponse(endpoint)
var v T
err := json.Unmarshal(body, &v)
require.Nil(t, err)
return v
}调用它的代码如下所示:
assertHTTPResponseOK[*GRPCResponse](t, "some-endpoint")所讨论的JSON对象如下所示:
{"str":"hello", "enu": "Type2"}我收到了一个错误,大意是:
json: cannot unmarshal string into Go struct field GRPCResponse.enu of type EnumType从类似的问题中,我看到了通常的建议是使用jsonpb.Unmarshal或protojson.Unmarshal而不是典型的json.Unmarshal。
在更改解组函数时,我还必须将T更改为protoreflect.ProtoMessage。但是,这阻止了我将指向v的指针传递给Unmarshal,因为它是指向接口的指针,而不是接口。当然,我也不能传入一个零指针(而不是使用v的地址)。
所以我的问题是:
是否有一种方法可以让这个通用对象的指针满足接口protoreflect.ProtoMessage
发布于 2022-04-19 21:46:04
最后,我传入了我正在解编组的对象。
obj := new(GRPCResponse)
assertHTTPResponseOK[*GRPCResponse](t, ctx, "some-endpoint", obj)func assertHTTPResponseOK[T protoreflect.ProtoMessage](t *testing.T, ctx context.Context, endpoint string, object T) {
body, err := GetResponse(endpoint)
require.Nil(t, err)
err = protojson.Unmarshal(body, object)
require.Nil(t, err)
}发布于 2022-05-17 05:36:42
下面是一个泛型友好的proto解组器,它避免传递第二种类型,而代价是一个反射调用来查看指针内的类型并调用它的构造函数。
var msg T // Constrained to proto.Message
// Peek the type inside T (as T= *SomeProtoMsgType)
msgType := reflect.TypeOf(msg).Elem()
// Make a new one, and throw it back into T
msg = reflect.New(msgType).Interface().(T)
errUnmarshal := proto.Unmarshal(body, msg)https://stackoverflow.com/questions/71928719
复制相似问题