Go - Defer Statement
The defer
statement defers the execution of a function until the surrounding function returns.
The deferred call’s arguments are evaluated immediately.
main.go
go
1package main
2
3import "fmt"
4
5func main() {
6 defer fmt.Println("world")
7
8 fmt.Println("hello")
9}
bash
$go run main.go
hello
world
Staking defer Statements
The deferred function calls are pushed onto a stack.
When the function returns the deferred calls are executed in LIFO order (last in first out).
main.go
go
1package main
2
3import "fmt"
4
5func main() {
6 fmt.Println("counting")
7
8 for i := 0; i < 5; i++ {
9 defer fmt.Println(i)
10 }
11
12 fmt.Println("done")
13}
bash
$go run main.go
counting
done
4
3
2
1
0