defer
The behavior of defer statements is straightforward and predictable. There are three simple rules:
- A deferred function’s arguments are evaluated when the defer statement is evaluated. In this example, the expression “i” is evaluated when the Println call is deferred. The deferred call will print “0” after the function returns.
1 | func a() { |
- Deferred function calls are executed in Last In First Out order after the surrounding function returns.
This function prints “3210”:1
2
3
4
5func b() {
for i := 0; i < 4; i++ {
defer fmt.Print(i)
}
} - Deferred functions may read and assign to the returning function’s named return values.
In this example, a deferred function increments the return value i after the surrounding function returns. Thus, this function returns 2:1
2
3
4
5
6
7
8
9
10
11
func main() {
fmt.Println(c())
// will print
// 2
}
func c() (i int) {
defer func() { i++ }()
return 1
}