如何投射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
谢谢!
如何投射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
谢谢!
好的,我发现它
reflect.Value
具有如下功能Interface()
它转换为interface{}
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)
这将其转换到接口{}。我们如何将其转换为实际类型? – Matt
Go,@Matt不可能。没有不安全或手动类型转换(至少在Go 1中),您不能重新创建泛型。 –
https://github.com/bpgriner/golang-reflection-custom-type – bpgriner