是否可以使用反射来做类似于类型切换的事情?

Is it possible to do something similar to a type switch using reflection?

我需要根据反映的值的类型做不同的事情。

value := reflect.ValueOf(someInterface)

我想做一些具有以下效果的事情:

if <type of value> == <type1> {
    do something
} else if <type of value> == <type2> {
    do something
}

这类似于 go 代码中的类型切换。

如果要遍历结构的字段,则可以使用类型开关根据字段的类型执行不同的操作:

value := reflect.ValueOf(s)
for i := 0; i < value.NumField(); i++ {
    field := value.Field(i)
    if !field.CanInterface() {
        continue
    }
    switch v := field.Interface().(type) {
    case int:
        fmt.Printf("Int: %d\n", v)
    case string:
        fmt.Printf("String: %s\n", v)
    }
}

https://play.golang.org/p/-B3PWMqWTo