Back to all posts
programming golang go

Go Defer

0 min read (83 words)

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.

Go code example showing multiple defer statements executing in LIFO order
sh-3.2$ go run switch.go 
hello
defer 4
defer 3
defer 2
defer 1

Nice blog about Defer, Panic and Recover.

Dmitry Golovach
About

Dmitry Golovach

Principal Network Engineer and AI enthusiast. Always learning, always building.

Share this post

All posts