Recursion

This section will go over the basic ideas of recursion and how that works in golang

Golang, like many other programming languages, supports recursive calls to functions. Here we will look at the classic example of recursion, getting the n-th fibonacci number. Here's how we do that in golang

package main

import "fmt"

func factorial(n int) int {
  // base cases
  if n <2 {
    return 1
  }
  // recursive case
  return n * factorial(n-1)
}
func main() {
  fmt.Println(fact(7))
  fmt.Println(fact(10))
  fmt.Println(fact(15))
}

There is nothing crazy about this function, and the implementation is very similar to other languages. In golang however, we can have a recursive closure function, which we can implement as follows:

package main

import "fmt"

func main() {
  // for a recursive closure, we need to explicitly
  // declare the function with a typed var before it is defined.
  var fib func(n int) int
  fib = func(n int) int {
    if n < 2 {
      return n
    }
    // since fib was previously declared in main,
    // Go knows which function to call with fib here.
    return fib(n-1) + fib(n-2)
  }
  fmt.Println(fib(7))
}

Last updated