Error handling

Deferred argument evaluation

The function value and argument values are evaluated when the defer executes, while the call itself runs later. A closure can instead read a captured variable at execution time. Deferred calls execute in reverse registration order when the surrounding function returns or unwinds. Example output: '2\n1'.

Formal Syntax & Structure

go syntaxgo
defer f(x)

Working Example

Example Snippetgo
package main
import "fmt"
func main() {  n := 1  defer fmt.Println(n)  defer func() { fmt.Println(n) }()  n = 2}
Go Reference