oop - Using reflection to call a method and return a value -


using question calling method name starting point, wanted call method name , value.

package main  import "fmt" import "reflect"  type t struct{}  func (t *t) foo() {     fmt.println("foo") }  type mystruct struct {     id int }  type person struct {     name string     age  int }  func (t *t) bar(ms *mystruct, p *person) int {     return p.age  }  func main() {     var t *t     reflect.valueof(t).methodbyname("foo").call([]reflect.value{})     var ans int     ans = reflect.valueof(t).methodbyname("bar").call([]reflect.value{reflect.valueof(&mystruct{15}), reflect.    valueof(&person{"dexter", 15})}) } 

playground link, http://play.golang.org/p/e02-kpdq_p

however, following error:

prog.go:30: cannot use reflect.valueof(t).methodbyname("bar").call([]reflect.value literal) (type []reflect.value) type int in assignment  [process exited non-zero status]  

what should differently return value? tried using type conversion , making int, compiler said couldn't []reflect.value.

call returns []reflect.value slice. need element slice in order type conversion. once have reflect.value instance can call int() value int64.

var ans int64 ans = reflect.valueof(t).methodbyname("bar").call([]reflect.value{     reflect.valueof(&mystruct{15}),      reflect.valueof(&person{"dexter", 15})})[0].int() fmt.println(ans) 

playground


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -