This is a creation in Article, where the information may have evolved or changed.
What closures are, closures are entities that are composed of functions and their associated reference environments (that is, closures = functions + reference environments).
This section can be see: http://www.cnblogs.com/ghj1976/archive/2013/02/08/2909364.html
The closure contains the external environment variable value, but the value of the environment variable is not the same as the anonymous function as the parameter copy, but the actual reference (or pointer, anyway a meaning), when the external variables change, the value of the closure can be used naturally change.
According to this principle, it is clear why several of the closure scenarios listed below are calculated as the corresponding values.
The following example is from: http://blog.csdn.net/liugao15/article/details/8296064
Example 1
Main
Import "FMT"
Main () {
fn [ten]func ()
i:= 0;i<len(FN); i++{
fn[i]=func() {
FMT. Println (i)
}
}
for _,f:=rangefn{
F ()
}
}
Output value:
10
10
10
10
10
10
10
10
10
10
Exit code 0, process exited normally.
Principle: When executing f (), I uses a pointer to the I previously defined, and since the loop has already been completed, it all shows 10.
Example 2
Main
"FMT"
Main () {
fn [ten]func(int)
i:= 0;i<len(FN); i++{
FN[I]=MAKE_FN ()
}
This IDEpointer is used in i,f:=//closures
F (i)
}
}
func int) {
func int) {
FMT. Println (i)
}
}
Output:
0
1
2
3
4
5
6
7
8
9
Exit code 0, process exited normally.
The following example is from: http://lelouchhe.github.com/one_thing_about_closure_in_go/
Example 3
Main
Import (
"FMT"
"Time"
)
Main () {
i:= 0;i<; i++{
func () {
FMT. Println (i)
}()
}
time. Sleep (1e9)
}
This output is all 100, because this loop is running faster than Goroutine, Goroutine has not started, the for loop is over, and the value of I is 100, so I naturally within the closure is 100.