Understanding Deferred Call Argument Evaluation
In Go, the "defer" statement is often used to ensure specific actions are taken at the end of a surrounding function. However, it is important to note that the arguments passed to the deferred call are not executed immediately.
According to the Go Spec, "each time a 'defer' statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked."
To elaborate, the function to be deferred (the "deferred function") and its associated parameters are evaluated right away. However, the actual execution of the deferred function is delayed until the surrounding function completes.
Example Explanation
Consider the following Go 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") }
In this example:
Therefore, the deferred function call's arguments ("defered line" in this case) are evaluated immediately when the defer statement is executed, setting up the function and its arguments for later execution.
The above is the detailed content of How Does Go Handle Deferred Function Call Argument Evaluation?. For more information, please follow other related articles on the PHP Chinese website!