How Defer Works Under the Hood
How Defer Works Under the Hood
Here’s how Go’s defer works internally:
type _defer struct {
sp uintptr // stack pointer
pc uintptr // program counter
fn *funcval // function address
link *_defer // pointer to next defer, links multiple defers
}This structure forms a linked list. Each time you declare a defer, it gets inserted at the head of the list.
The compiler does two things:
- At each
deferdeclaration, it inserts a call todeferproc() - Before each
return, it inserts a call todeferreturn()
return is not atomic. It happens in steps:
- Save return values (if any)
- Run deferred functions (if any)
- Execute the final
retinstruction
This explains why deferred functions run in reverse order (LIFO). Each new defer goes to the front of the list, so the last declared runs first.