[英]How do I use a type switch to determine the type of a protoreflect.MessageDescriptor?
I am writing a protoc generation plugin using the protogen package.我正在使用protogen package 编写一个 protoc 生成插件。
I am looping the fields of a message and want to determine if a field is one of a few different message types.我正在循环消息的字段,并想确定一个字段是否是几种不同的消息类型之一。
It is possible to get the name of the message type as a string using:可以使用以下方法将消息类型的名称作为字符串获取:
field.Desc.Message().FullName() // mypackage.MyMessage
The problem with this approach is that I will need to switch against a string, which is error-prone:这种方法的问题是我需要切换一个容易出错的字符串:
switch field.Desc.Message().FullName(){
case "mypackage.MyMessage":
case "mypackage.MyMessage2":
}
Is there anyway to do this using a type assertion?无论如何使用类型断言来做到这一点? I tried to create an instance of the message using dynamicpc , but the type assertion does not work:
我尝试使用dynamicpc创建消息的实例,但类型断言不起作用:
mt := dynamicpb.NewMessage(field.Desc.Message())
msg, ok := mt.(*mypackage.MyMessage) // ok is false despite field.Desc.Message().FullName() returning mypackage.MyMessage
The function dynamicpb.NewMessage
doesn't create a Golang structure mypackage.MyMessage
. dynamicpb.NewMessage
dynamicpb.NewMessage 不会创建 Golang 结构mypackage.MyMessage
。 Instead it creates a data structure that marshals into the same binary form as mypackage.MyMessage
相反,它创建了一个数据结构,可以编组为与
mypackage.MyMessage
相同的二进制形式
Have a look inside the Message
data structure :查看
Message
数据结构内部:
// Operations which modify a Message are not safe for concurrent use.
type Message struct {
typ messageType
known map[protoreflect.FieldNumber]protoreflect.Value
ext map[protoreflect.FieldNumber]protoreflect.FieldDescriptor
unknown protoreflect.RawFields
}
It is just a storage for field values along with with fields' metadata.它只是字段值以及字段元数据的存储。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.