Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast reflect.Value to its type?

Tags:

reflection

go

How to cast reflect.Value to 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!

like image 354
Alex Avatar asked Jun 23 '13 15:06

Alex


2 Answers

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

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

type MyInt int var x MyInt = 7 v := reflect.ValueOf(x) y := v.Interface().(float64) // y will have type float64. fmt.Println(y) 
like image 184
sharewind Avatar answered Sep 18 '22 23:09

sharewind


Ok, I found it

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

like image 29
Alex Avatar answered Sep 18 '22 23:09

Alex