Stacking defers in Golang

Deferred function calls are pushed onto a stack. When a function returns, its deferred calls are executed in last-in-first-out order.

Example:

package main

import "fmt"

func main() {
  fmt.Println("counting")
  for i := 0; i < 5; i++ {
    defer fmt.Println(i)
  }
  fmt.Println("done")
}
Output:
$ go run defer-multi.go
counting
done
4
3
2
1
0