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 main23import "fmt"45func main() {6 defer fmt.Println("world")78 fmt.Println("hello")9}
bash
$go run main.gohelloworld
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 main23import "fmt"45func main() {6 fmt.Println("counting")78 for i := 0; i < 5; i++ {9 defer fmt.Println(i)10 }1112 fmt.Println("done")13}
bash
$go run main.gocountingdone43210