Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Defer

  • 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)

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