This is a creation in
Article, where the information may have evolved or changed.
57. Toad Notes Go language--closures
Closures are entities that are composed of functions and their associated reference environments (that is, closures = functions + reference environments).
The sample code is as follows:
Package Main
Import "FMT"
func Exfunc (nint)func() {
sum:=n
a:=func() {// assigns the anonymous function as a value to variable a(Go does not allow function nesting.)
// However you can use anonymous functions to implement nested functions)
FMT. Println (sum+1)// call a variable outside this function
}// There is no () anonymous function is not executed immediately
returna
}
func Main () {
myfunc:=exfunc (ten)
myFunc ()
myanotherfunc:=exfunc ()
myanotherfunc ()
myFunc ()
myanotherfunc ()
}
Execution results are as follows
11
21st
11
21st
Conditions in which the closure function appears:
1. The nested function refers to an external variable that is not the function, and the external variable is not a "global variable"
2. The nested function is isolated (returned by the parent function or assigned to a separate individual).
The parent function where the referenced variable resides has ended.
Objects are data that is attached to the behavior, and closures are data-attached behaviors.
Friendship Link
Http://www.cnblogs.com/Jifangliang/archive/2008/08/05/1260602.html
Http://blog.sina.com.cn/s/blog_487109d101018fcx.html