Trace defer evaluation and LIFO
Trace defer evaluation and LIFO
When a defer statement executes, its function value and arguments are evaluated and saved immediately. The actual calls run later in last-in, first-out (LIFO) order. A deferred closure that reads an outer variable may observe its later value instead of a saved argument.
package main
import ( "fmt")
func demo() { n := 1 defer fmt.Println("saved", n) defer func() { fmt.Println("current", n) }() n = 3 fmt.Println("body")}func main() { demo()}Both calls are deferred. The direct call saves n=1 at registration. The closure captures n and reads 3 when it runs. The closure was registered last, so it runs first.
Expected output:
bodycurrent 3saved 1Modify a named result deliberately
package main
import ( "fmt")
func value() (n int) { defer func() { n += 2 }(); return 5 }func main() { fmt.Println(value())}The return statement sets n to 5 before deferred calls execute. The closure modifies n before it is returned to the caller. Use this ability sparingly for explicit cleanup or result handling. An unnamed return result cannot be changed by simply modifying a separate local variable after its return value has been evaluated.
Expected output:
7Try it locally
Defer printing "first" and then "second" in a function, print "body" normally, and call the function.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Errors and cleanup 09: Trace defer evaluation and LIFO
Check the lesson objective before moving on.
When is the argument of defer fmt.Println(n) evaluated?
What order do deferred calls normally run in?