A defer statement defers the execution of a function until the surrounding function returns.
The deferred function's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.
```
package main
import (
"fmt"
"os"
)
func main() {
f := createFile("/tmp/defer.txt")
defer closeFile(f)
writeFile(f)
}
func createFile(p string) *os.File {
f, err := os.Create(p)
if err != nil {
panic(err)
}
return f
}
func writeFile(f *os.File) {
fmt.Println("writing")
}
func closeFile(f *os.File) {
err := f.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
```
Deferred function calls are pushed onto a stack. When a function returns, its deferred calls are executed in last-in-first-out order.