Home >Backend Development >Golang >What Happens to Deferred Function Arguments in Go?

What Happens to Deferred Function Arguments in Go?

DDD
DDDOriginal
2024-12-20 12:37:11631browse

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:

  • Function Value: The function to be deferred is evaluated as usual.
  • Parameters: The parameters to the deferred function are also evaluated immediately.

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:

  1. def() Arguments Evaluation: The parameter "defered line" is evaluated immediately.
  2. def() Function Evaluation: The def() function is called, printing "tier up" and "defered line."
  3. Deferred Function Evaluation: The return value of def() is evaluated, which is a function that prints "clean up."
  4. Deferred Function Execution: When main() returns, the deferred function is executed, printing "clean up."

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!

Statement:
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