Explain the execution order of defer statements and when exactly a deferred function executes relative to the return values of the surrounding function.
Last updated
Deferred calls run in LIFO order (last registered runs first), and their arguments are evaluated when the
deferstatement executes, not when the call runs.On
return x, the return value is set first, then deferred functions run, then control goes back to the caller.So with named return values a deferred function can modify the result (e.g.
return 5plus a deferredresult++yields 6), commonly used to set errors inrecover.