TExcelTAD
Home › Go › Go Recursion

Go Recursion

A function is recursive when it calls itself. Recursion is a natural fit for problems that contain smaller copies of themselves: factorials, tree structures, nested folders, or splitting a list in half again and again.

Every recursive function needs two parts:

  1. A base case — a condition where it returns an answer directly, without calling itself.
  2. A recursive case — where it calls itself with a smaller problem that moves toward the base case.

Without a base case, the function would call itself forever until the program runs out of stack memory.

A first example: counting down

go · try it yourself
package main

import "fmt"

func countdown(n int) {
	if n == 0 { // base case
		fmt.Println("Go!")
		return
	}
	fmt.Println(n)
	countdown(n - 1) // recursive case: a smaller problem
}

func main() {
	countdown(3)
}
3
2
1
Go!

Factorial

The factorial of n (written n!) is n × (n-1) × … × 1. It can be defined in terms of itself: n! = n × (n-1)!, with 0! = 1.

go · try it yourself
package main

import "fmt"

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

func main() {
	for i := range 6 {
		fmt.Printf("%d! = %d\n", i, factorial(i))
	}
}
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120

How does factorial(4) work? Each call waits for the one below it:

Call Waits for Returns
factorial(4) 4 * factorial(3) 24
factorial(3) 3 * factorial(2) 6
factorial(2) 2 * factorial(1) 2
factorial(1) base case 1

Fibonacci and the cost of naive recursion

Each Fibonacci number is the sum of the two before it. The direct recursive version is elegant but very slow for big inputs, because it recalculates the same values over and over. Storing results already computed — memoization — fixes that.

go · try it yourself
package main

import "fmt"

var calls int

func fib(n int) int {
	calls++
	if n < 2 {
		return n
	}
	return fib(n-1) + fib(n-2)
}

func fibMemo(n int, memo map[int]int) int {
	if n < 2 {
		return n
	}
	if v, ok := memo[n]; ok {
		return v
	}
	memo[n] = fibMemo(n-1, memo) + fibMemo(n-2, memo)
	return memo[n]
}

func main() {
	fmt.Println(fib(20), "using", calls, "calls")
	fmt.Println(fibMemo(80, map[int]int{}))
}
6765 using 21891 calls
23416728348467685

Recursion over nested data

Recursion shines with data that nests to an unknown depth, like folders inside folders. Here a struct contains a slice of its own type:

go · try it yourself
package main

import (
	"fmt"
	"strings"
)

type Folder struct {
	Name     string
	Files    int
	Children []Folder
}

func totalFiles(f Folder) int {
	total := f.Files
	for _, child := range f.Children {
		total += totalFiles(child)
	}
	return total
}

func printTree(f Folder, depth int) {
	fmt.Printf("%s%s (%d)\n", strings.Repeat("  ", depth), f.Name, f.Files)
	for _, child := range f.Children {
		printTree(child, depth+1)
	}
}

func main() {
	root := Folder{"home", 2, []Folder{
		{"docs", 5, nil},
		{"photos", 1, []Folder{
			{"2024", 40, nil},
			{"2025", 12, nil},
		}},
	}}
	printTree(root, 0)
	fmt.Println("Total files:", totalFiles(root))
}
home (2)
  docs (5)
  photos (1)
    2024 (40)
    2025 (12)
Total files: 60

Recursion or a loop?

Recursion Loop
Best for trees, nested data, divide-and-conquer flat sequences, simple counting
Memory one stack frame per call constant
Readability often closer to the math definition often more direct

Note: Go's goroutine stacks grow automatically, so deep recursion rarely crashes — but a missing base case still ends with a fatal stack overflow error once the stack reaches its 1 GB limit. Go does not optimise tail calls, so for very long linear sequences prefer a loop.

Test yourself

What is a base case?

  1. The first line of a function
  2. The condition where a recursive function returns without calling itself
  3. The largest input
  4. A function in the main package

Why is naive recursive Fibonacci slow?

  1. Recursion is always slow in Go
  2. It recomputes the same subproblems many times
  3. Maps are slow
  4. It uses floats