问题描述
reflect.TypeOfType
reflect.TypeOfType
type
type
Typetype
或者任何处理它的建议?
Or any suggestion to handle it?
package main
import (
"fmt"
"reflect"
)
type Article struct {
Id int64 `json:"id"`
Title string `json:"title",sql:"size:255"`
Content string `json:"content"`
}
func IdentifyItemType(name string) interface{} {
var item interface{}
switch name {
default:
item = Article{}
}
return item
}
func main() {
i := IdentifyItemType("name")
item := i.(Article)
fmt.Printf("Hello, item : %v
", item)
item2 := i.(reflect.TypeOf(i)) // reflect.TypeOf(i) is not a type
fmt.Printf("Hello, item2 : %v
", item2)
}
推荐答案
如果你需要开启外层接口的类型{}你不需要反射.
If you need to switch on the type of the outer interface{} you wont need reflection.
switch x.(type){
case int:
dosomething()
}
...但是如果您需要在界面中打开属性的类型,那么您可以这样做:
...but if you need to switch on the type of the attributes in an interface then you can do this:
s := reflect.ValueOf(x)
for i:=0; i<s.NumValues; i++{
switch s.Field(i).Interface().(type){
case int:
dosomething()
}
}
我还没有找到更简洁的方法,我很想知道它是否存在.
I haven't found a cleaner way, I'd love to know if it exists.
这篇关于golang 类型断言使用reflect.Typeof()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!