-
Notifications
You must be signed in to change notification settings - Fork 1
/
FuncPool.go
40 lines (36 loc) · 870 Bytes
/
FuncPool.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package util
import (
"fmt"
"reflect"
)
// 动态模式函数调用
type FuncPool map[string]interface{}
// 调用
func (m FuncPool) Call(name string, args ...interface{}) (out []interface{}, err error) {
if m[name] == nil {
return nil, fmt.Errorf("Func \"%s\" not exists ", name)
}
v := reflect.ValueOf(m[name])
vs := v.Type().NumIn()
if len(args) < vs {
return nil, fmt.Errorf("[%s] Not enough params: need %v, given %v", name, vs, len(args))
}
in := make([]reflect.Value, vs)
for i, _ := range in {
in[i] = reflect.ValueOf(args[i])
}
out = make([]interface{}, v.Type().NumOut())
ret := v.Call(in)
for i, _ := range out {
out[i] = ret[i].Interface()
}
return
}
// 出错则panic
func (m FuncPool) MustCall(name string, args ...interface{}) (out []interface{}) {
o, err := m.Call(name, args...)
if err != nil {
panic(err)
}
return o
}