Section 8 of 11
defer
finally, but attached to a statement and scoped to the function.
LIFO order and argument evaluation
go.dev playground
Try it: The two prints differ: defer evaluates ARGUMENTS immediately, but a closure reads the variable at call time.
- Runs on normal return, early return, and panic. It is your try-with-resources.
- Multiple defers run LIFO.
- Arguments are evaluated at the defer statement; the CALL happens at function exit.
- Scope is the FUNCTION, not the block — defer inside a loop accumulates and is a classic fd leak. Extract the body into its own function.