-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
40 lines (34 loc) · 1.17 KB
/
main.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
// Go lang Closures.
// Creates a closure function and passes it to another function as a parameter.
// This function in turn calls the closure.
package main
import (
"fmt"
)
func main() {
closureA := createClosure(1)
useClosure(2, closureA)
useClosure(5, closureA)
}
// createClosure creates two closures. One around a variable defined within the function
// and another around a function parameter
func createClosure(closureInput int) func(int) int {
fmt.Println("Create Closure")
closureVar := -10
fmt.Println(fmt.Sprintf("%-30v : %d", "Initial closureInput ", closureInput))
fmt.Println(fmt.Sprintf("%-30v : %d", "Initial closureVar ", closureVar))
return func(a int) int {
closureInput += a
closureVar -= a
fmt.Println(fmt.Sprintf("%-30v : %d", "closureInput ", closureInput))
fmt.Println(fmt.Sprintf("%-30v : %d", "closureVar ", closureVar))
return closureInput + closureVar
}
}
// useClosure takes a function with a closure var and use it.
// It is a dramatic way of showing closures since this function has absolutely no
// reference to the "closed" variable
func useClosure(a int, f func(int) int) int {
fmt.Println("Use Closure, input: ", a)
return f(a)
}