sajad torkamani

Basic usage

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

The deferred function’s arguments are evaluated immediately but the function call isn’t executed until the surrounding function returns.

For example, the following program:

package main

import "fmt"

func main() {
	defer fmt.Println("world")

	fmt.Println("hello")
}

Outputs:

"hello"
"world

Stacking defers

Deferred functions are pushed into a stack. When the surrounding function returns, its deferred calls are executed so that the most recently deferred function (the items at the top of the stack) are executed first.

For example, the following program:

package main

import "fmt"

func main() {
	fmt.Println("counting")

	for i := 0; i < 10; i++ {
		defer fmt.Println(i)
	}

	fmt.Println("done")
}

Outputs:

counting
done
9 # From the most recent deferred call
8
7
6
5
4
3
2
1
0 # From the earliest deferred call
Tagged: Golang