25. Defer
Wait Until I am done!

Defer Statement

defer is special keyword in Go to schedule some action until function returns. Defer is mostly used in cleanup task that should be done when returning from a function. Defer find its use similar to what finally does in some programming languages. Semantic for defer is
defer some_action
main.go
1
func sayHello() {
2
3
defer fmt.Println("Performing cleanup")
4
fmt.Println("Hello, There!")
5
6
}
7
func main() {
8
sayHello()
9
}
Copied!
Here, call to print cleanup is scheduled to be executed when function returns. Hello, There is printed first and then Performing cleanup.

Panic scenarios

The benefit of using defer keyword is that Go guarantees it will be carried out even if there is panic.
main.go
1
func doPanic() {
2
defer fmt.Println("Performing cleanup")
3
panic("Oops")
4
fmt.Println("Hello, There")
5
}
6
func main() {
7
doPanic()
8
}
Copied!
In this case, defer will still print Performing cleanup.

Blog Posts

Defer, Panic, and Recover - go.dev
Last modified 2yr ago