使用反射是否可以实现类似于类型开关(type switch)的功能?

huangapple go评论77阅读模式
英文:

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 &lt;type of value&gt; == &lt;type1&gt; {
    do something
} else if &lt;type of value&gt; == &lt;type2&gt; {
    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 &lt; value.NumField(); i++ {
	field := value.Field(i)
	if !field.CanInterface() {
		continue
	}
	switch v := field.Interface().(type) {
	case int:
		fmt.Printf(&quot;Int: %d\n&quot;, v)
	case string:
		fmt.Printf(&quot;String: %s\n&quot;, v)
	}
}

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

huangapple
  • 本文由 发表于 2015年9月5日 03:19:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/32405165.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定