This is a creation in Article, where the information may have evolved or changed.
Reprint http://blog.sina.com.cn/s/blog_487109d101018fcx.html slightly do processing
Find this when looking for " closures" information:
Http://www.cnblogs.com/Jifangliang/archive/2008/08/05/1260602.html
The explanations are very clear and the examples are very simple.
closures are the whole of "function" and "reference environment".
use go to rewrite his example here:
Package Main Import "FMT" func exfunc (n int) func() { sum:=n a:= func () { > //Assign 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 } //not here .()anonymous functions do not execute immediately return a } func Main () { Myfunc:=exfunc (10) MyFunc () Myanotherfunc:=exfunc (20) Myanotherfunc () MyFunc () Myanotherfunc () } |
This function also has another notation:
func exfunc (n int) func() { sum:=n return func () { c16> // anonymous function directly at the return point fmt. Println(sum+1) } } Another example: Package Main Import "FMT" Func exfunc (n int) func () { return func () { n++// The external variable is added here 1 Fmt. PRINTLN (N) } }
Func Main () { MyFunc: = Exfunc (10) MyFunc ()// here output One Myanotherfunc: = Exfunc (20) Myanotherfunc ()// here output + MyFunc ()//12 Myanotherfunc ()//22 // Call the MyFunc () function again , and the result is 12, resulting in the following two points //1. The modification of variables in the external function of the inner function is a reference to the variable //2. once a variable is referenced, its function ends, and the variable is not immediately destroyed, and the lifetime of the reference variable and the resulting function variable is consistent } |
| Package main Import ( FMT " ) Func adder () func (int) int { sum: = 0 innerfunc: = func (x int) int { su M + = x return sum } return innerfunc } Func Main () { pos, neg: = Adder (), adder () for I: = 0; i < ten; i++ { Fmt. Println (POS (i), neg ( -2*i)) } } |
results: The closure is referenced to the external environment, and each invocation of an anonymous function produces an environment; the difference from the previous example is that the enclosing variable for the outer function is introduced here: Sum, called multiple times Adder () , once per call: Adder () a closure environment is generated: sum and anonymous functions, multiple calls to the closure function, shared sum; every Adder () the closure environment generated by the call is isolated from each other; 0 0 1-2 3-6 6-12 10-20 15-30 21-42 28-56 36-72 45-90 |