This is a creation in Article, where the information may have evolved or changed.
闭包is a combination of a function and its associated reference environment (i.e., closure = function + reference environment). [1] In the program design, 对象 is attached to the behavior of data, and 闭包 is attached to the data of the behavior.
Let's take a look at the practical examples of closures in the Go language:
Package MainImport"FMT"func Exfunc(N int)func(){ sum := n A: = func () {sum++ fmt. Println (SUM) //Call a variable outside this function }return a}func Main(){ myFunc := Exfunc (ten) myanotherfunc: = exfunc (myfun) C () //These two output one by one ,myFunc ()myanotherfunc ( )//The output of these two sentences, A Myanotherfunc () }
The anonymous function and the variable num in exfunc form a closure. Running this code will give you the following results:
11122122
Closures can be thought of as a class that executes in a function that alters its reference environment during execution. For example main , in a function, we create two separate closures, and the process of two closures changes the respective referencing environment.
If you want to know the closure of the system, you can view the references [3]
Reference:
1. The closed-loop discussion on function programming (Closure)
2. Closures in Go
3. Concept, form and application of closures