func Call(m map[string]interface{}, name string, params ...interface{}) ([]reflect.Value, error) { f := reflect.ValueOf(m[name]) if len(params) != f.Type().NumIn() { return nil, errors.New("the number of input params not match!") } in := make([]reflect.Value, len(params)) for k, v := range params { in[k] = reflect.ValueOf(v) } return f.Call(in), nil }
使用:
func Test(a, b string) (string,error) { return a +" "+ b,nil }
m := map[string]interface{}{"test":Test} ret, err := Call(m, "test", "hello", "world") if err != nil { log.Fatalln("method invoke error:", err) } fmt.Println(ret)
有疑问加站长微信联系(非本文作者)