Defer

Defers the execution of a method until the end of the calling function. The arguments are evaluated at the time defer is called.

func main() {
	i := 3

	defer fmt.Print(i)

	i += 3

	fmt.Printf("%d ", i)
}

// Output: 6 3

Stacking

Defers are executed LIFO

func main() {
	for i := 0; i < 10; i++ {
		defer fmt.Printf("%v ", i)
	}
}

// Output: 9 8 7 6 5 4 3 2 1 0