Skip to content

How to write a Recursive Function in Go

Posted on:July 8, 2020 at 10:40 PM

I don’t know about you, but when I started programming the term Recursion made me quiver a bit. I think this is a natural response honestly. New things can be scary! I also did not understand the importance or the potential impact that using Recursion in your code could have. If you don’t have a solid grasp on Recursion, you are in luck! I am going to discuss how you can harness the power of Recursion and use it in your Go programs.

So, What is Recursion?

the repeated application of a procedure or definition

A common use of Recursion in programming is calling a function, inside of the same function. Let me show you an example:

package main
import (
	"fmt"
)

func main() {
	n := factorial(4)
	fmt.Println(n)
}

func factorial(n int) int {
	if n == 0 {
		return 1
	}
	return n * factorial(n-1)
}
// 4 * 3 * 2 * 1

main:

func main() {
	n := factorial(4)
	fmt.Println(n)
}

Quick note: in every Recursive function, there needs to be a “base case”. The base case is most commonly an if statement that when evaluated to “true” will stop calling the function within the function (stop recursion) and will allow the program to return out of the function

factorial:

func factorial(n int) int {
	if n == 0 {
		return 1
	}
	return n * factorial(n-1)
}

n * factorial(n-1):

func factorial(n int) int {
  // n = 4
	if n == 0 {
		return 1
  }
	return n * factorial(n-1)
}
func factorial(n int) int {
  // n = 3
	if n == 0 {
		return 1
  }
	return n * factorial(n-1)
}
func factorial(n int) int {
  // n = 2
	if n == 0 {
		return 1
  }
	return n * factorial(n-1)
}
func factorial(n int) int {
  // n = 1
	if n == 0 {
		return 1
  }
	return n * factorial(n-1)
}
func factorial(n int) int {
  // n = 0
	if n == 0 {
    // true, return 1
		return 1
  }
  return n * factorial(n-1)
}

main:

func main() {
  n := factorial(4)
  fmt.Println(n)
  // 24
}

In Summary

I hope you have enjoyed learning about Recursion. Although, this example is not overly complex, I hope that you can walk away after reading this post with a better understanding of the principles of Recursion and apply them in your workflow. I will say, there should be a level of caution when writing recursive functions. If your base case is not sound, you could find yourself in a position where your function can continually call itself and inevitably cause a stack overflow. However, when done right, Recursion allows us to write clean, DRY, and efficient code.

Next week I will be discussing Pointers, JSON Marshalling, and JSON Unmarshalling. See you then!

Never miss a post, subscribe to my Substack!