Defer


Every defer statement is executed after the enclosing function ends. In reverse order. (Similar to END block in Perl, similar to with context in python)


examples/defer/defer.go
package main

import "fmt"

func main() {
    fmt.Println("first")
    defer fmt.Println("one")
    fmt.Println("second")
    defer fmt.Println("two")
    fmt.Println("third")
}

$ go run defer.go

first
second
third
two
one