The function is waiting until the surrounding function returns.
Note: the deferred call’s arguments are evaluated immediately, but executed at the end
func main() {
defer fmt.Println("defer 1")
fmt.Println("hello")
}
sh-3.2$ go run switch.go
hello
defer 1
We can stack deferred function calls - calls are executed in last-in-first-out order. Useful when something needs to be done at the end of the function.
sh-3.2$ go run switch.go
hello
defer 4
defer 3
defer 2
defer 1
Nice blog about Defer, Panic and Recover.