-
-
Notifications
You must be signed in to change notification settings - Fork 455
Expand file tree
/
Copy pathmonkeypatching.go
More file actions
37 lines (29 loc) · 600 Bytes
/
Copy pathmonkeypatching.go
File metadata and controls
37 lines (29 loc) · 600 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
package main
import (
"fmt"
)
// define the function as variable
var patchableFunc = func(i int) int {
return i * 2
}
func testFunc() {
// save the original func
originalFunc := patchableFunc
// restore the original func via defer at the end of the func
defer func() {
patchableFunc = originalFunc
}()
// call the function
fmt.Println(patchableFunc(1))
// change the function
patchableFunc = func(i int) int {
return i * 3
}
// call the function again
fmt.Println(patchableFunc(2))
}
func main() {
fmt.Println(patchableFunc(3))
testFunc()
fmt.Println(patchableFunc(4))
}