-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecorator.go
More file actions
49 lines (42 loc) · 904 Bytes
/
decorator.go
File metadata and controls
49 lines (42 loc) · 904 Bytes
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
41
42
43
44
45
46
47
48
49
package main
import (
"fmt"
"reflect"
)
func Decorator(decoPtr, fn interface{}) (err error) {
var decoratedFun, targetFunc reflect.Value
decoratedFun = reflect.ValueOf(decoPtr).Elem()
targetFunc = reflect.ValueOf(fn)
v := reflect.MakeFunc(targetFunc.Type(),
func(in []reflect.Value) (out []reflect.Value) {
fmt.Println("before")
out = targetFunc.Call(in)
fmt.Println("after")
return
})
decoratedFun.Set(v)
return
}
func foo(a, b, c int) int {
fmt.Printf("%d, %d, %d \n", a, b, c)
return a + b + c
}
func bar(a, b string) string {
fmt.Printf("%s, %s \n", a, b)
return a + b
}
func main() {
//通过函数签名
type MyFoo func(int, int, int) int
var myfoo MyFoo
err := Decorator(&myfoo, foo)
if err != nil {
panic(err)
}
i := myfoo(1, 2, 3)
fmt.Println("result: ", i)
//不用函数签名
mybar := bar
_ = Decorator(&mybar, bar)
mybar("Hello", "world!")
}