Getting started with Go programming – Defer

A defer statement defers the execution of a function until the surrounding function returns.

package main
import "fmt"
func main() {
defer fmt.Println("world")
fmt.Println("hello")
}

Output

hello
world

deferred function calls are executed in Last In First Out order after the surrounding function returns.


package main
import "fmt"

func main() {
callMe()
}
func callMe() {
defer fmt.Println("world")
fmt.Println("hello")
for i := 0; i < 5; i++ {
defer fmt.Printf("%d ", i)
}
}

Output:

hello
4 3 2 1 0 world

If you see the output its clear that the deferred function calls are executed in Last In First Out order after the surrounding function returns. For more information refer to the https://golang.org/ref/spec#Defer_statements

 

Leave a Reply

Your email address will not be published. Required fields are marked *