In Go, a deferred function call allows you to execute code after the surrounding function returns. However, the behavior of deferred calls can be confusing if you don't understand how arguments are handled.
The quote from "A Tour of Go" states that "the deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns." This means that:
Let's examine the provided example:
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") }
When main() is called, the following happens:
Understanding the distinction between argument evaluation and function execution is crucial for using deferred calls effectively in Go. Arguments are evaluated immediately when the defer statement is executed, while the function body is only executed when the enclosing function returns. This allows you to control the order in which actions are performed and to avoid potential issues related to unexpected function behavior.
The above is the detailed content of Go Deferred Calls: Are Arguments Evaluated Immediately or Upon Function Execution?. For more information, please follow other related articles on the PHP Chinese website!