How to cast a reflection. Do you know his type?

How to apply reflection. Specify its type?

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 

Thanks!

+8
reflection go
source share
2 answers

Ok i found it

reflect.Value has an Interface() function that converts it to interface{}

+10
source share
 concreteCat,_ := reflect.ValueOf(cat).Interface().(Cat) 

see http://golang.org/doc/articles/laws_of_reflection.html fox

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

All Articles