-
Notifications
You must be signed in to change notification settings - Fork 1
/
Defer.go
62 lines (48 loc) · 1013 Bytes
/
Defer.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
53
54
55
56
57
58
59
60
61
62
package main
import (
"fmt"
"time"
)
func main() {
// Timer example using Defer
stop := startTimer("Sample Timer")
defer stop()
defer fmt.Println("Have a nice day! :) ")
deferInsideFunction()
// What will be printed here? Hello or World?
m := "Hello"
defer fmt.Println("set variable to Hello and defer print: ", m)
m = "world"
fmt.Println("set variable to World and print: ", m)
// What happens here ?
for i := 0; i < 10; i++ {
defer func(j int) {
fmt.Println(j)
}(i)
}
// ?
for i := 0; i < 10; i++ {
defer func() {
fmt.Println(i)
}()
}
// ?
for i := 0; i < 10; i++ {
defer fmt.Println(i)
}
time.Sleep(1 * time.Second)
fmt.Println("done")
}
func startTimer(name string) func() {
t := time.Now()
fmt.Println(name, "started")
return func() {
d := time.Now().Sub(t)
fmt.Println(name, "took", d)
}
}
func deferInsideFunction() {
fmt.Println("Working in function")
defer fmt.Println("Defer inside function")
fmt.Println("Done working inside function")
}