Invoking a function

While the type of the function shows information about it, in order to call a function, we need to use its value.

We will pass the function a list of argument values and get back the ones returned by the function call:

func main() {
for _, f := range []interface{}{Foo, Bar, Baz, Qux} {
v, t := reflect.ValueOf(f), reflect.TypeOf(f)
name := runtime.FuncForPC(v.Pointer()).Name()
in := make([]reflect.Value, t.NumIn())
for i := range in {
switch a := t.In(i); a.Kind() {
case reflect.Int:
in[i] = reflect.ValueOf(42)
case reflect.String:
in[i] = reflect.ValueOf("42")
case reflect.Slice:
switch a.Elem().Kind() {
case reflect.Int:
in[i] = reflect.ValueOf(21)
case reflect.String:
in[i] = reflect.ValueOf("21")
}
}
}
out := v.Call(in)
fmt.Printf("%q %v%v ", name, in, out)
}
}

A full example is available here: https://play.golang.org/p/jPxO_G7YP2I.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.127.37