我需要根据所反映的值的类型来做不同的事情。使用反射可以做类似于类型切换的东西吗?
value := reflect.ValueOf(someInterface)
我想要做的东西,有以下作用:
if <type of value> == <type1> {
do something
} else if <type of value> == <type2> {
do something
}
这类似于一种类型的开关在Go代码做一些事情。
我需要根据所反映的值的类型来做不同的事情。使用反射可以做类似于类型切换的东西吗?
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)
}
}
这将工作 - 但如果字段为零,则不行。有没有办法直接通过字段的类型? – Ziffusion
@扩大:类型开关工作在字段类型,而不是值。例如:https://play.golang.org/p/U82wLxOS98 –
@Ziffusion:类型开关对字段类型起作用,而不是值。请参阅:https://play.golang.org/p/U82wLxOS98 –
只是双重检查:'TYPE1 '和'type2'是动态的,对吗?另外,你想达到什么目的? –
实际上,它们是在go代码中定义的类型。 – Ziffusion
然后你不能使用类型开关吗? –