In Go, a closure is a special function that can access variables in the scope it is defined, even if the function is called elsewhere. The "execution immediately" and "not executing immediately" of closures mainly depend on the definition and how they are called.
1. Definition of closure
A closure is a function that captures variables in the scope it is defined. For example:
func makeAdder(base int) func(int) int { return func(delta int) int { return base + delta } }
In this example, makeAdder returns a closure that can access the base variable at its definition
2. Closures that are not executed immediately
A closure that is not executed immediately means that a closure is defined but is called at some subsequent moment. For example:
func main() { adder := makeAdder(10) // Define closure (adder(5)) // Call closure, output 15}
In this example, makeAdder(10) returns a closure, but does not execute it immediately. We assign it to the variable adder, and then execute the closure when the subsequent call to add(5) is called.
3. Immediate execution of closure
A closure that is executed immediately refers to calling it immediately while defining it. This usage is not common in Go, but may be used in some scenarios. For example:
func main() { result := func(base int) func(int) int { return func(delta int) int { return base + delta } }(10)(5) // Define and execute closure immediately (result) // Output 15}
In this example, func(base int) func(int) int is a function that returns a closure. While defining it, we immediately pass in parameter 10 and call the returned closure, passing in parameter 5, and finally output the result.
4. Immediate execution of anonymous functions
In Go, anonymous functions can also be executed immediately, similar to the immediate execution of closures. For example:
func main() { result := func() int { return 42 }() (result) // Output 42}
Here is an anonymous function func() int, and it is called immediately through () while it is defined.
Summarize
Closures that are not executed immediately:
After defining the closure, store it in the variable and call it later.
Closures that are executed immediately:
Calling it immediately while defining a closure is usually used in some special scenarios such as initializing operations or simplifying code logic.
In actual development, closures that are not executed immediately are more common because they can be called multiple times, using variables captured by closures to achieve some flexible functions.
This is the article about the immediate execution and non-immediate execution of go language closures. For more relevant go language closures, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!