英文:
Is it possible to do something similar to a type switch using reflection?
问题
根据所反映的值的类型,我需要做不同的事情。
value := reflect.ValueOf(someInterface)
我想要做的事情具有以下效果:
if <value的类型> == <type1> {
做一些事情
} else if <value的类型> == <type2> {
做一些事情
}
这类似于Go代码中的类型切换操作。
英文:
I need to do different things based on the type of the value being reflected.
value := reflect.ValueOf(someInterface)
I'd like to do something that has the following effect:
if <type of value> == <type1> {
do something
} else if <type of value> == <type2> {
do something
}
This is something similar to what a type switch does in go code.
答案1
得分: 2
如果你正在遍历结构体的字段,你可以使用类型切换来根据字段的类型执行不同的操作:
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("整数: %d\n", v)
case string:
fmt.Printf("字符串: %s\n", v)
}
}
链接:https://play.golang.org/p/-B3PWMqWTo
英文:
If you are iterating over fields of a struct, you can use a type switch to perform different actions based off of the field's type:
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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论