Call a function (method), with multiple arguments and returns, of a struct by
name during run-time in Golang. (run-time reflection)
This is an advanced example of .
Run Code on Go Playground
package main
import (
"fmt"
"reflect"
)
type DemoStruct struct {
s string
i int
f float64
}
func (d *DemoStruct) DemoFunc(s string, i int, f float64) (string, int, float64, DemoStruct) {
return s, i, f, *d
}
func main() {
ds := DemoStruct{"sacca", 1, 3.14}
// call DemoFunc() method
fmt.Println(ds.DemoFunc("dukkha", 0, 1.414))
// call DemoFunc() method by Name
retv := reflect.ValueOf(&ds).MethodByName("DemoFunc").Call([]reflect.Value{
reflect.ValueOf("dukkha"),
reflect.ValueOf(13),
reflect.ValueOf(1.414),
})
fmt.Println(retv[0].String())
fmt.Println(retv[0].Interface().(string))
fmt.Println(retv[1].Int())
fmt.Println(retv[1].Interface().(int))
fmt.Println(retv[2].Float())
fmt.Println(retv[2].Interface().(float64))
fmt.Println(retv[3].Interface().(DemoStruct))
}
References: