(Xvii) golang-- closure (simple)

The so-called closure: a reference that is a function of the overall environment and its associated combined;

First, there is a small example below, the final output what is it? 11, 12, it is the output?

 Code Description above:
(. 1) addUpper is a function that returns the func (int) int;

(2) func (int) int n outside the reference function, so this anonymous function and n form a closure;

(3) It can be appreciated that the closures are based, is a function of operation, n being a field;

(4) When we repeatedly call the function f, because n is initialized once, so each time you call accumulating;

(5) clear key closure, is to analyze the function and returns it to a reference variable which closure is formed;

 

Closures small example: to determine whether the file name suffixes are jpg, if it is to return the file name directly, or to add .jpg file

 

 We use the normal method to achieve a small example:

 

 Closure notice the difference between normal and did not? Closures only need to pass a ".jpg" on the line, but normal is required every time you need to pass.

The closure What are the advantages of it?

Obviously:

(1) a function of the internal variable can be read;

(2) Let the variable long-term storage in the memory, and not after the end of the call garbage collection in recycling, because the variable has been cited other functions;

Amount shortcomings are obvious: a great memory consumption;

Guess you like

Origin www.cnblogs.com/xiximayou/p/11882545.html