Skip to content

Instantly share code, notes, and snippets.

@jony4
Last active May 27, 2019 02:00
Show Gist options
  • Save jony4/fdf0472ec4b90e641ae115da284f74e6 to your computer and use it in GitHub Desktop.
Save jony4/fdf0472ec4b90e641ae115da284f74e6 to your computer and use it in GitHub Desktop.
Likely PHP's call_user_func_array() or Javascritpt's callback(jsonObject)
package main
import (
"errors"
"fmt"
"reflect"
)
func main() {
funcs := map[string]interface{}{"foo": foo, "bar": bar}
Call(funcs, "foo")
Call(funcs, "bar", 1, 2, 3)
}
// Call is magic func.
func Call(m map[string]interface{}, name string, params ...interface{}) (result []reflect.Value, err error) {
f := reflect.ValueOf(m[name])
if len(params) != f.Type().NumIn() {
err = errors.New("The number of params is not adapted")
return
}
in := make([]reflect.Value, len(params))
for k, param := range params {
in[k] = reflect.ValueOf(param)
}
result = f.Call(in)
return
}
func foo() {
fmt.Println("test")
}
func bar(a, b, c int) {
fmt.Println(a, b, c)
}
@jony4
Copy link
Author

jony4 commented Sep 29, 2018

result:

test
1 2 3

@jony4
Copy link
Author

jony4 commented Sep 29, 2018

@jony4
Copy link
Author

jony4 commented Sep 29, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment