2

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.

Community
  • 1
  • 1
Alec
  • 4,235
  • 1
  • 34
  • 46

1 Answers1

3

Call returns []reflect.Value which is a slice. You need to get an element from the slice in order to do the type conversion. Once you have a reflect.Value instance you can call Int() to get the value as an 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

Logiraptor
  • 1,496
  • 10
  • 14