如何将 reflect.Value 转换为它的类型?

新手上路,请多包涵

如何将 reflect.Value 转换为它的类型?

 type Cat struct {
    Age int
}

cat := reflect.ValueOf(obj)
fmt.Println(cat.Type()) // Cat

fmt.Println(Cat(cat).Age) // doesn't compile
fmt.Println((cat.(Cat)).Age) // same

谢谢!

原文由 Alex 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 438
2 个回答

好的,我找到了

reflect.Value 有一个函数 Interface() 将它转换成 interface{}

原文由 Alex 发布,翻译遵循 CC BY-SA 3.0 许可协议

concreteCat,_ := reflect.ValueOf(cat).Interface().(Cat)

请参阅 http://golang.org/doc/articles/laws_of_reflection.html 狐狸示例

type MyInt int
var x MyInt = 7
v := reflect.ValueOf(x)
y := v.Interface().(float64) // y will have type float64.
fmt.Println(y)

原文由 sharewind 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题