Junior · Go foundations
Defer arguments and return values
When are deferred function arguments evaluated?
Try explaining this aloud before opening the answer. State your assumptions and trace a boundary case.
x := 1
defer fmt.Println(x)
defer func() { fmt.Println(x) }()
x = 2Reveal a strong answer
The function value and arguments of a deferred call are evaluated when the defer statement executes; the call itself runs when the surrounding function returns. Deferred calls run in last-in, first-out order.
A deferred closure can read variables at execution time, so defer fmt.Println(x) and defer func(){fmt.Println(x)}() need not print the same value. Named result variables can also be modified by a deferred closure after the return expression is assigned.
Use defer to make cleanup ownership clear, but do not accumulate thousands of open resources by deferring inside a long-running loop. Move one iteration into a function when each iteration should close its resource promptly.
Common trap
A deferred call does not postpone evaluation of its already supplied arguments.
Try it
x starts at1; defer fmt.Println(x); set x to2. What prints? What if the deferred code is a closure reading x?
Worked solution
The direct deferred call prints1 because its argument was captured at defer time. A closure reading x at return prints2. If both are deferred, the later defer runs first. Test resource close errors when they affect correctness instead of ignoring them reflexively.
Change the constraint
Why does deferring file.Close inside a huge file-processing loop keep too many descriptors open?
How did you do?
Self-assessment, not a compiler pass or interview score. Explain the reasoning unaided before marking understood.
Not marked. Progress stays on this browser, separate from course completion.
Primary references
Checked 2026-10-20. Use documentation for your pinned runtime, driver and tool version.