types – 使用reflect.Typeof()的golang类型断言
发布时间:2020-12-16 19:21:06 所属栏目:大数据 来源:网络整理
导读:我试图用字符串值(名称)来识别结构. reflect.TypeOf返回Type. 但是类型断言需要一种类型. 如何将Type转换为类型? 或任何处理它的建议? http://play.golang.org/p/3PJG3YxIyf package mainimport ("fmt""reflect")type Article struct { Id int64 `json:"id
|
我试图用字符串值(名称)来识别结构.
reflect.TypeOf返回Type. 但是类型断言需要一种类型. 如何将Type转换为类型? 或任何处理它的建议? 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 : %vn",item)
item2 := i.(reflect.TypeOf(i)) // reflect.TypeOf(i) is not a type
fmt.Printf("Hello,item2 : %vn",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()
}
}
我还没有找到一种更清洁的方式,我很想知道它是否存在. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
