defer
statements marks a function to be executed at the end of current function.
Defer statement is an ordinary function call prefixed by the keyword defer
.
defer someFunction()
A deferred function is executed once the function that contains the defer
statement returns. Actual call to the deferred function occurs when the enclosing function: - executes a return statement - falls off the end - panics
Example:
https://codeeval.dev/gist/80abac053ba1f668811e32685d84882a
If a function has multiple deferred statements, they form a stack. The last defer
is the first one to execute after the enclosing function returns, followed by subsequent calls to preceding defer
s in order (below example returns by causing a panic):
https://codeeval.dev/gist/229ee9bd2ba470d486599317fec212ff
Deferred functions have their arguments evaluated at the time defer
executes:
https://codeeval.dev/gist/f75bfd0acd30591ee84a804744fb85b4
If a function has named return values, a deferred anonymous function within that function can access and update the returned value even after the function has returned: