The go language supports anonymous functions. Anonymous functions can form function closures. Anonymous functions are useful when you want to define an inline function that does not need to be named.
Package Mainimport "FMT"//This "INTSEQ" function returns another anonymous function defined inside the INTSEQ,//The returned anonymous function has wrapped the variable i, thus forming a closure func intseq () func () int { I: = 0 return func () int { i + = 1 return i }}func main () { //We call the INTSEQ function and <span the result style= "F Ont-family:arial, Helvetica, Sans-serif; > (function) </span><span style= "font-family:arial, Helvetica, Sans-serif;" > Assign to a function nextint,</span> //The Nextint function has its own I variable, which is updated each time the call is called. //The initial value of I here is determined by the time the intseq is called. Nextint: = Intseq () //Call several nextint to see the effect of the closure FMT. Println (Nextint ()) FMT. Println (Nextint ()) FMT. Println (Nextint ()) //In order to confirm that the state of the closure is independent of the INTSEQ function, create one. newints: = Intseq () FMT. Println (Newints ())}
Output
<strong>$ Go Run closures.go1231</strong>
In the next section, we will learn the last feature of the function: recursion.
Next example: Go by Example:recursion.
English original
Go by Example:closures