go / intermediate
Snippet
Understanding Defer Argument Evaluation Timing
Arguments to a deferred function are evaluated immediately when the defer line is reached, not when the actual deferred function is executed at the end of the surrounding block. This behavior is crucial when passing values or calling tracking functions.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package mainimport "fmt"func trace(message string) string {fmt.Println("Evaluating trace:", message)return message}func execute() {action := "Start"defer fmt.Println("Deferred action executed:", trace(action))action = "Finish"fmt.Println("Main execution completed")}func main() {execute()}
Breakdown
1
defer fmt.Println("Deferred action executed:", trace(action))
Registers the print statement, evaluating the helper function argument immediately.
2
trace(action)
Executed during evaluation of the defer statement, capturing 'Start'.
3
action = "Finish"
Modifies the variable, but the deferred print argument has already been resolved.
4
fmt.Println("Main execution completed")
Prints before the deferred statement finally prints its evaluated arguments.