This is a creation in Article, where the information may have evolved or changed.
30. Toad Notes Go language-about closures
The anonymous function of Go is a closed packet.
Concept
Closures are blocks of code that can contain free (unbound object-specific) variables that are not defined within the code block or in any global context, but are defined in the context in which the code block is defined. The code block to execute (because free variables are included in the code block, so these free variables and the objects they refer to are not freed) provide a binding computing environment (scope) for free variables.
The value of closures
The value of a closure is that it can be used as a function object or as an anonymous function, which means, for a type system, not only to represent the data but also to represent the code. Most languages that support closures use functions as first-level objects, meaning that these functions can be stored in variables as arguments to other functions, and most importantly, they can be dynamically created and returned by a function.
Closures in the Go language also refer to variables outside the function. The closure implementation ensures that as long as the closure is used, the variables referenced by the closure will persist.
Code
Package Main
Import (
"FMT"
)
Func Main () {
var jint = 5
A: =func () func () {
vari int = 10
Returnfunc () {
Fmt. Printf ("I,j:%d,%d\n", I, J)
}
}()
A ()
J *= 2
A ()
}
Perform
I,j:10, 5
I,j:10, 10
In the above example, the closure function that the variable a points to refers to the values of the local variables I and j,i are isolated, cannot be modified outside the closure, changes the value of J, and then calls a again, discovering that the result is a modified value.
In the closure function that the variable a points to, only the internal anonymous function can access the variable I and cannot be accessed by other means, thus guaranteeing the security of I.