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.
  1. package main
  2. import "fmt"
  3. // This function intSeq returns another function,
  4. // which we define anonymously in the body of intSeq.
  5. // The returned function closes over the variable i to form a closure.
  6. func intSeq() func() int {
  7. i := 0
  8. return func() int {
  9. i++
  10. return i
  11. }
  12. }
  13. func main() {
  14. // We call intSeq, assigning the result (a function) to nextInt.
  15. // This function value captures its own i value,
  16. // which will be updated each time we call nextInt.
  17. nextInt := intSeq()
  18. // See the effect of the closure by calling nextInt a few times.
  19. fmt.Println(nextInt())
  20. fmt.Println(nextInt())
  21. fmt.Println(nextInt())
  22. // To confirm that the state is unique to that particular function,
  23. // create and test a new one.
  24. newInts := intSeq()
  25. fmt.Println(newInts())
  26. }
1
2
3
1

Recursion

Go supports recursive functions). Here’s a classic example.
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