Home > Backend Development > Golang > Go Deferred Calls: Are Arguments Evaluated Immediately or Upon Function Execution?

Go Deferred Calls: Are Arguments Evaluated Immediately or Upon Function Execution?

Mary-Kate Olsen
Release: 2024-12-06 00:44:11
Original
591 people have browsed it

Go Deferred Calls: Are Arguments Evaluated Immediately or Upon Function Execution?

Deferred Call's Arguments: Immediate Evaluation vs. Function Execution

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.

Evaluation vs. Execution

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:

  • Evaluation: When you defer a function call, the function value and its parameters are evaluated and captured. This occurs when the enclosing function is called.
  • Execution: After the enclosing function has returned, the deferred function is executed.

Example Explanation

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")
}
Copy after login

When main() is called, the following happens:

  1. The defer statement evaluates the argument to def, which is the constant string "defered line."
  2. The def function is called with "defered line," printing "tier up" and "defered line."
  3. The return value of def is a function that prints "clean up." This function is not yet executed.
  4. main() prints "main."
  5. Once main() returns, the deferred function is executed, printing "clean up."

Conclusion

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template