// Chapter 31 example: defer runs a call when the function returns. // Run with: go run exercises/31/01-defer.go package main import "fmt" func check(n int) { fmt.Println("Start") defer fmt.Println("End") if n < 0 { fmt.Println("Negative, so return early") return } fmt.Println("Not negative") } func stack() { defer fmt.Println("Deferred first") defer fmt.Println("Deferred second") defer fmt.Println("Deferred third") fmt.Println("The body is done") } func valueNow() { x := 1 defer fmt.Println("Deferred x:", x) x = 2 fmt.Println("x at the end:", x) } func main() { check(5) check(-5) fmt.Println() stack() fmt.Println() valueNow() }