Using the question about calling a method by name as a starting point, I wanted to call a method by name and actually do something with the 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, I get the following error:
prog.go:30: cannot use reflect.ValueOf(t).MethodByName("Bar").Call([]reflect.Value literal) (type []reflect.Value) as type int in assignment
[process exited with non-zero status]
What should I do differently to actually return a value? I tried using type conversion and making it an int
, but the compiler said that it couldn't []reflect.Value
.