如何投射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