Home >Backend Development >Golang >What Happens to Deferred Function Arguments in Go?
Evaluating Deferred Function Arguments
Question: A quote in The Tour of Go states that "the deferred call's arguments are evaluated immediately." What does this mean and what is actually evaluated?
Answer:
In Go, defer statements delay the execution of a function until the enclosing function returns. However, the evaluation of the deferred function's arguments occurs immediately.
Breaking Down the Evaluation Process:
The specification states that for each "defer" statement:
The actual function call is not executed until the surrounding function returns.
Example:
Consider the following code:
func def(s string) func() { fmt.Println("tier up") fmt.Println(s) return func() { fmt.Println("clean up") } } func main() { defer def("defered line")() fmt.Println("main") }
Evaluation Sequence:
Conclusion:
When a defer statement is used, the parameters of the deferred function are evaluated immediately. This process ensures that the function has access to the most current values of the variables when it is executed. However, the actual execution of the deferred function is delayed until the surrounding function returns.
The above is the detailed content of What Happens to Deferred Function Arguments in Go?. For more information, please follow other related articles on the PHP Chinese website!