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:
- A base case — a condition where it returns an answer directly, without calling itself.
- 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
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.
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.
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:
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 overflowerror 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?
- The first line of a function
- The condition where a recursive function returns without calling itself
- The largest input
- A function in the main package
Why is naive recursive Fibonacci slow?
- Recursion is always slow in Go
- It recomputes the same subproblems many times
- Maps are slow
- It uses floats