You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The defer method is an in - and out-stack structure.
6
+
`` `
7
+
package main
8
+
9
+
import(
10
+
"fmt"
11
+
)
12
+
13
+
func main(){
14
+
defer func(){
15
+
fmt.Println("1")
16
+
} ()
17
+
defer func(){
18
+
fmt.Println("2")
19
+
} ()
20
+
defer func(){
21
+
fmt.Println("3")
22
+
} ()
23
+
24
+
fmt.Println("4")
25
+
fmt.Println("5")
26
+
27
+
return
28
+
}
29
+
30
+
// output
31
+
// 4
32
+
// 5
33
+
// 3
34
+
// 2
35
+
// 1
36
+
`` `
37
+
38
+
### defer Aborts execution
39
+
40
+
The defer stack operation after return will not be ignored
41
+
`` `
42
+
package main
43
+
44
+
import(
45
+
"fmt"
46
+
)
47
+
48
+
func main(){
49
+
defer func(){
50
+
fmt.Println("1")
51
+
} ()
52
+
defer func(){
53
+
fmt.Println("2")
54
+
} ()
55
+
56
+
return
57
+
58
+
defer func(){
59
+
fmt.Println("3")
60
+
} ()
61
+
defer func(){
62
+
fmt.Println("4")
63
+
} ()
64
+
}
65
+
66
+
// output
67
+
// 2
68
+
// 1
69
+
`` `
70
+
71
+
### defer
72
+
73
+
** * Avoid using this type of operation as it is not recommended because it is not readable **
74
+
* If the return value is not declared as a specific variable, defer will not change the return value variable
75
+
76
+
`` `
77
+
package main
78
+
79
+
import(
80
+
"fmt"
81
+
)
82
+
83
+
func main(){
84
+
da := testA()
85
+
fmt.Println(da)
86
+
87
+
db := testB()
88
+
fmt.Println(db)
89
+
}
90
+
91
+
// Function body: name return value
92
+
func testA()(data string) {
93
+
data = "OLD"
94
+
defer func(){
95
+
data = "NEW"
96
+
} ()
97
+
return res
98
+
}
99
+
100
+
// Function body: non-name return value
101
+
func testB()(string) {
102
+
data := "OLD"
103
+
defer func(){
104
+
data = "NEW"
105
+
} ()
106
+
return res
107
+
}
108
+
109
+
// output
110
+
// NEW
111
+
// OLD
112
+
`` `
113
+
114
+
# # # defer summary
115
+
116
+
* defer is used to **ensure** that a function call is performed later in a program's execution, usually for purposes of cleanup. defer is often used where e.g. ensure and finally would be used in other languages.
117
+
118
+
* defer in Go is like the C++ destructor; the Go area of C++ "destructors" is for functions, not objects.
119
+
The * defer is the structure statement ** added when the function executes. It is the default, not the specified structure statement.
0 commit comments