Defer
What is it
Schedules function calls to execute BEFORE the surrounding function returns.
- commonly used for cleanup tasks like closing files or releasing resources.
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.
- A returnstatement that specifies results sets theresult parametersbefore any deferred functions are executed.
- deferred functions are invoked immediately before the surrounding function returns
Meaning, the return parameter i has already been set to return value 1 immediate as the function starts executing.
- Then, the deferfunctions begin execution.
- Then, the return parameter iis set again to2sincei++is executed via thedefer func().
- Since there is only one i,iis no longer1, it is a2.
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 */