golang类型断言使用reflect.Typeof() [英] golang type assertion using reflect.Typeof()

查看:594
本文介绍了golang类型断言使用reflect.Typeof()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用字符串值(名称)来标识结构。
reflect.TypeOf 返回类型



但是类型断言需要一个类型



如何铸造类型类型



或者有任何建议来处理它?<​​b>

http://play.golang.org/p/3PJG3YxIyf

 包主

导入(
fmt
反映

类型结构{
Id int64`json:id`
标题字符串`json:title,sql:size:255`
内容字符串`json:content`
}


func IdentifyItemType(name string)interface {} {
var item interface {}
开关名称{
默认值:
item = Article {}
}
返回项目
}

func main(){

i:= IdentifyItemType(name)
item:= i。(Article)
fmt.Printf(您好,item:%v \ n,item)
item2:= i。(reflect.TypeOf(i))// reflect.TypeOf(i)不是类型
fmt.Printf Hello,item2:%v \\\
,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()
}
}

我还没有找到更清晰的方式,我很想知道它是否存在。


I've tried to identify a struct with string value(name). reflect.TypeOf returns Type.

But type assertion needs a type.

How can I casting Type to type?

Or any suggestion to handle it?

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)

}

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆