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 defer declaration, it inserts a call to deferproc()
  • Before each return, it inserts a call to deferreturn()

return is not atomic. It happens in steps:

  1. Save return values (if any)
  2. Run deferred functions (if any)
  3. Execute the final ret instruction

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.