27.2 · defer: what runs, when, and what it can change
defer looks simple until it meets a return value, a loop or a throw. Most puzzles hide in when the returned value is computed and whether the defer statement was reached.
Mental model. Three facts: the return value is computed first, a defer runs every time its scope exits, and a defer only exists once execution has passed the line.
Return values and scopes
What a defer can and cannot change, and how it behaves in loops, throws and early exits.
- A function returns x and a defer changes x afterwards. What does the caller receive, for a value, an inout, a class instance and a string being built?
The return expression is evaluated first, the result is held, then the deferred blocks run, then the function actually returns. So for plain() the defer does… - When does a defer inside a loop, a throwing function or an early-exit branch run, and when is it never registered?
A defer belongs to the scope it is written in and runs whenever that scope is left: normal end, return, break, continue or a thrown error. In a loop body the…