Home > Backend Development > Golang > How Does Go Handle Deferred Function Call Argument Evaluation?

How Does Go Handle Deferred Function Call Argument Evaluation?

DDD
Release: 2024-12-10 06:57:16
Original
731 people have browsed it

How Does Go Handle Deferred Function Call Argument Evaluation?

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

In this example:

  • The deferred function value (def("defered line")) is evaluated, which involves calling def with the argument "defered line". This prints "tier up" and the argument.
  • The return value of def, which is an anonymous function, is deferred but not executed yet.
  • The remaining code in main (fmt.Println("main")) is executed.
  • Once main returns, the deferred function is executed, printing "clean up".

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template