2013-06-23 89 views
8

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

謝謝!

回答

10

好的,我發現它

reflect.Value具有如下功能Interface()它轉換爲interface{}

+15

這將其轉換到接口{}。我們如何將其轉換爲實際類型? – Matt

+0

Go,@Matt不可能。沒有不安全或手動類型轉換(至少在Go 1中),您不能重新創建泛型。 –

+0

https://github.com/bpgriner/golang-reflection-custom-type – bpgriner

21
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) 
+9

這就是如果你真的有這種類型的知識。如果你想申請一種盲類斷言,我實際上不確定它是可能的。 – Taye

+0

一個解決方案似乎是將'reflect.Value'保持原樣並簡單地將所有計算移動到使用反射包,而無需轉換回常規結構。你可以在[gongular]中看到這個(https://github.com/mustafaakin/gongular/blob/master/handler.go#L101)。相關:https://play.golang.org/p/Ok_q3lx490h – Xeoncross