简体   繁体   中英

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.

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:

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 . Instead it creates a data structure that marshals into the same binary form as mypackage.MyMessage

Have a look inside the Message data structure :

// 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM