Go Language Function Closures
Go supports anonymous functions, which can form closures. An anonymous function is an "inline" statement or expression. The advantage of anonymous functions is that they can directly use variables within the function without declaration.
In the following example, we create a function called getSequence()
, which returns another function. The purpose of this function is to increment the variable i
within the closure. 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, with i starting at 0 */
nextNumber := getSequence()
/* Call nextNumber function, increment i by 1 and return */
fmt.Println(nextNumber())
fmt.Println(nextNumber())
fmt.Println(nextNumber())
/* Create a new function nextNumber1 and check the result */
nextNumber1 := getSequence()
fmt.Println(nextNumber1())
fmt.Println(nextNumber1())
}
The above code execution result is:
1
2
3
1
2