forked from ardanlabs/gotraining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample4.go
40 lines (30 loc) · 870 Bytes
/
example4.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
// All material is licensed under the Apache License Version 2.0, January 2004
// http://www.apache.org/licenses/LICENSE-2.0
// Sample program to show how anonymous functions and closures work.
package main
import "fmt"
func main() {
var n int
// Declare an anonymous function and call it.
func() {
fmt.Println("Direct:", n)
}()
// Declare an anonymous function and assign it to a variable.
f := func() {
fmt.Println("Variable:", n)
}
// Call the anonymous function through the variable.
f()
// Defer the call to the anonymous function till after main returns.
defer func() {
fmt.Println("Defer 1:", n)
}()
// Set the value of n to 3 before the return.
n = 3
// Call the anonymous function through the variable.
f()
// Defer the call to the anonymous function till after main returns.
defer func() {
fmt.Println("Defer 2:", n)
}()
}