types - golang 类型断言使用 reflect.Typeof()

标签 types go typeof assertion

我尝试使用字符串值(名称)来识别结构。 reflect.TypeOf 返回 Type

但是类型断言需要一个type

如何将 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 : %v\n", item)
    item2 := i.(reflect.TypeOf(i))  // reflect.TypeOf(i) is not a type
    fmt.Printf("Hello, item2 : %v\n", item2)

}

最佳答案

如果需要开启外部接口(interface)的类型{}则不需要反射。

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()
  }
}

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

关于types - golang 类型断言使用 reflect.Typeof(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27900568/

相关文章:

javascript - 如何在功能组件中使用 React Typescript 键入任何参数

Scala 函数/方法参数化返回类型

go - 类型别名在 Go 中如何工作?

go - json : cannot unmarshal string into Go struct field

go - 为什么 Go 中存在类型 int

C# - 将 SomeClass 传递给函数而不是 typeof(SomeClass)

C typedef 正确用例

php - php 和 golang 之间的 lz4 问题

r - 从其他 data.frame R 分配 data.frame 列类