-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfunction_closures.go
52 lines (44 loc) · 1.01 KB
/
function_closures.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
41
42
43
44
45
46
47
48
49
50
51
52
package main
import "fmt"
/**
Function closures
Go functions may be closures. A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense the function is "bound" to the variables.
*/
func getFunction(operator string) func(int, int) int {
switch operator {
case "+":
return func(a, b int) int { return a + b }
case "-":
return func(a, b int) int { return a - b }
case "*":
return func(a, b int) int { return a * b }
case "/":
return func(a, b int) int { return a / b }
default:
return nil
}
}
func logFunc(a, b int, op string) {
f := getFunction(op)
if f == nil {
fmt.Println("Can't execute operator " + op)
} else {
fmt.Printf("%d %s %d = %d\n", a, op, b, f(a, b))
}
}
func main() {
a := 8
b := 2
logFunc(a, b, "+")
logFunc(a, b, "-")
logFunc(a, b, "*")
logFunc(a, b, "/")
logFunc(a, b, "%")
}
/**** Results ****
8 + 2 = 10
8 - 2 = 6
8 * 2 = 16
8 / 2 = 4
Can't execute operator %
*****************/