본문 바로가기

Programing/Golang

이름으로 함수 호출하기

package main import "fmt" import "reflect" import "errors" func foo() { fmt.Println("we are running foo") } func bar(a, b, c int) { fmt.Println("we are running bar", a, b, c) } func ret() (bool, int) { return true, 100 } 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 main() { // nota bene: for perfect score: use reflection to build this map funcs := map[string]interface{} { "foo": foo, "bar": bar, "ret": ret, } Call(funcs, "foo") Call(funcs, "bar", 1, 2, 3) r, _ := Call(funcs, "ret") rBool := r[0].Interface().(bool) rInt := r[1].Interface().(int) fmt.Println("we are running ret", rBool, rInt) }


https://play.golang.org/p/U1e44xi3pqz