如何测试元素是否为 Any 类型

问题描述

如何在 Go 中测试结构的元素是否为 Any (protobuf): *any.Any 类型? 我想遍历结构的每个元素,并根据元素的类型做一个 switch case。 这是消息的字段描述符:

FieldDescriptor{Syntax: proto3,FullName:,Number: 3,Cardinality: optional,Kind: message,HasJSONName: true,JSONName:,HasPresence: true,Oneof:,Message: google.protobuf.Any}

这是我的代码

func doSomething(src protoreflect.Message) {
    src.Range(func(fd protoreflect.FieldDescriptor,v protoreflect.Value) bool {
            switch {
            case fd.IsList():
                // do something
            case fd.IsMap():
                // do something
            case fd.Message() != nil:
                // do something
            case fd.Kind() == protoreflect.BytesKind:
                // do something
            case *test if message is Any* :
                // do something
            default:
                // do something
            }
        return true
        })
}

我想要一个比 ex 更正确的方法

if fd.Message() != nil{
     fd.Message().FullName() == "google.protobuf.Any"
}

解决方法

您可以使用 switch case 进行类型检查。

 switch v := fd.(type) { 
    default:
        fmt.Printf("unexpected type %T",v)
    case string:
        //do something
    }