Closures
| Go supports anonymous functions, which can form closures). Anonymous functions are useful when you want to define a function inline without having to name it. |
|
package mainimport "fmt"// This function intSeq returns another function, // which we define anonymously in the body of intSeq. // The returned function closes over the variable i to form a closure.func intSeq() func() int { i := 0 return func() int { i++ return i }}func main() { // We call intSeq, assigning the result (a function) to nextInt. // This function value captures its own i value, // which will be updated each time we call nextInt. nextInt := intSeq() // See the effect of the closure by calling nextInt a few times. fmt.Println(nextInt()) fmt.Println(nextInt()) fmt.Println(nextInt()) // To confirm that the state is unique to that particular function, // create and test a new one. newInts := intSeq() fmt.Println(newInts())}
1
2
3
1
Recursion
package main
import "fmt"
// This fact function calls itself until it reaches the base case of fact(0).
func fact(n int) int {
if n == 0 {
return 1
}
return n * fact(n-1)
}
func main() {
fmt.Println(fact(7))
// Closures can also be recursive, but this requires the closure to be
// declared with a typed var explicitly before it’s defined.
var fib func(n int) int
fib = func(n int) int {
if n < 2 {
return n
}
return fib(n-1) + fib(n-2)
}
// Since fib was previously declared in main,
// Go knows which function to call with fib here.
fmt.Println(fib(7))
}
5040
13