Go language function closure
Go
language supports anonymous functions and can be used as closures. An anonymous function is an “inline” statement or expression. The advantage of anonymous functions is that you can use variables within the function directly without declaring it.
In the following example, we created a function getSequence()
to return another function The purpose of this function is to increment in the closure i
variable, the code is as follows:
Example
package main
import "fmt"
func getSequence() func() int {
i:=0
return func() int {
i+=1
return i
}
}
func main(){
/* NextNumber is a function where function i is 0 */
nextNumber := getSequence()
/* Call the nextNumber function, increment the i variable by 1 and return */
fmt.Println(nextNumber())
fmt.Println(nextNumber())
fmt.Println(nextNumber())
/* Create a new function nextNumber1 and view the results */
nextNumber1 := getSequence()
fmt.Println(nextNumber1())
fmt.Println(nextNumber1())
}
The result of the above code execution is:
1
2
3
1
2