Links

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
func sayHello() {
defer fmt.Println("Performing cleanup")
fmt.Println("Hello, There!")
}
func main() {
sayHello()
}
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
func doPanic() {
defer fmt.Println("Performing cleanup")
panic("Oops")
fmt.Println("Hello, There")
}
func main() {
doPanic()
}
In this case, defer will still print Performing cleanup.

Blog Posts