Schedules function calls to execute BEFORE
the surrounding function returns.
Without returns
, defer
executes after a non-defer execution.
func main() { defer fmt.Println("world") fmt.Println("hello") } /* hello world */
In below example, the defer
function increments the return value i
BEFORE the surrounding function returns.
return
statement that specifies results sets the result parameters
before any deferred functions are executed.Meaning, the return parameter i
has already been set to return value 1
immediate as the function starts executing.
defer
functions begin execution.i
is set again to 2
since i++
is executed via the defer func()
.i
, i
is no longer 1
, it is a 2
.func main() { c() } func c() (i int) { defer func() { i++ print(i) }() defer func() { print("third") }() defer func() { print("second") }() defer func() { print("first") }() print(i) return 1 } /* // i is initialized to a default int value of 0 0 // print(i) prints initial value // i is then set to return value 1, but function does not return yet first // Since defer is LIFO, last defer function is first to execute second third 2 // i++ print(i) // last element in stack // since return value is i, not what follows after "return", printing c() would result in 2 */