我试图用字符串值(名称)来识别结构。reflect.TypeOf
回报Type
.
但是类型断言需要一个type
.
我怎样才能铸造Type
to type
?
或者有什么建议可以处理吗?
http://play.golang.org/p/3PJG3YxIyf http://play.golang.org/p/3PJG3YxIyf
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\n", item)
item2 := i.(reflect.TypeOf(i)) // reflect.TypeOf(i) is not a type
fmt.Printf("Hello, item2 : %v\n", item2)
}
如果您需要打开外部接口的类型,则不需要反射。{}
switch x.(type){
case int:
dosomething()
}
...但是如果您需要在接口中打开属性的类型,那么您可以这样做:
s := reflect.ValueOf(x)
for i:=0; i<s.NumValues; i++{
switch s.Field(i).Interface().(type){
case int:
dosomething()
}
}
我还没有找到更干净的方法,我很想知道它是否存在。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)