Closures
We have introduced anonymous function syntax using some basic examples. Now that we have a fundamental understanding of how anonymous functions work, we will look at how we can use this powerful concept. Closures are a form of anonymous functions. Regular functions cannot reference variables outside of themselves; however, an anonymous function can reference variables external to their definition. A closure can use variables declared at the same level as the anonymous function's declared. These variables do not need to be passed as parameters. The anonymous function has access to these variables when it is called:
func main() {   i := 0   incrementor := func() int {     i +=1     return i     }   fmt.Println(incrementor())   fmt.Println(incrementor())   i +=10   fmt.Println(incrementor()) }
Code synopsis:
- We initialize a variable in the...