Recursion
suggest changeA recursive function is a function that calls itself. Recursion is a natural fit for problems that are defined in terms of smaller versions of themselves: trees, nested data, divide-and-conquer algorithms and backtracking searches.
Go supports recursion without any special syntax. This article covers how recursion works in Go, what happens when it goes too deep, recursive closures, recursive data structures and iterators, common algorithms, and when to replace recursion with a loop.
Basics: base case and recursive case
Every recursive function needs two parts:
- a base case that returns a result without recursing
- a recursive case that calls the function with a smaller problem, getting closer to the base case
package main
import "fmt"
func factorial(n int) int {
if n <= 1 { // base case
return 1
}
return n * factorial(n-1) // recursive case
}
func main() {
for i := range 6 {
fmt.Printf("%d! = %d\n", i, factorial(i))
}
fmt.Println("20! =", factorial(20))
}
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
20! = 2432902008176640000
factorial(4) calls factorial(3), which calls factorial(2) and so on until factorial(1) hits the base case. Then the results are multiplied on the way back up. Adding a depth parameter makes this visible:
package main
import (
"fmt"
"strings"
)
func factorial(n, depth int) int {
indent := strings.Repeat(" ", depth)
fmt.Printf("%sfactorial(%d)\n", indent, n)
if n <= 1 {
fmt.Printf("%s-> 1\n", indent)
return 1
}
res := n * factorial(n-1, depth+1)
fmt.Printf("%s-> %d\n", indent, res)
return res
}
func main() {
factorial(4, 0)
}
factorial(4)
factorial(3)
factorial(2)
factorial(1)
-> 1
-> 2
-> 6
-> 24
Each call has its own copy of parameters and local variables, stored in a stack frame. A frame stays alive until its call returns.
Stack growth and stack overflow
In C or Java, each thread has a fixed-size stack (often 1-8 MB), so deep recursion overflows quickly. Go is different: each goroutine starts with a small stack (a few KB) that the runtime grows automatically, by copying it to a bigger memory block, when needed.
As a result, recursion a million levels deep is not a problem:
package main
import "fmt"
type Node struct {
Value int
Next *Node
}
func sumRec(n *Node) int {
if n == nil {
return 0
}
return n.Value + sumRec(n.Next)
}
func sumIter(n *Node) int {
total := 0
for ; n != nil; n = n.Next {
total += n.Value
}
return total
}
func main() {
var head *Node
for i := range 1_000_000 {
head = &Node{Value: i % 10, Next: head}
}
fmt.Println(sumRec(head), sumIter(head))
}
4500000 4500000
The stack is not unlimited. The default maximum is 1 GB on 64-bit systems (250 MB on 32-bit). Exceeding it is a fatal error, not a panic, so recover can't catch it and the program crashes.
Here's a function without a base case. We lower the limit with debug.SetMaxStack so it crashes faster:
package main
import (
"fmt"
"runtime/debug"
)
func countDown(n int) int {
return countDown(n-1) + 1 // no base case
}
func main() {
debug.SetMaxStack(1 << 20) // 1 MB instead of the default 1 GB
defer func() {
fmt.Println("recovered:", recover()) // never runs
}()
fmt.Println(countDown(10))
}
runtime: goroutine stack exceeds 1048576-byte limit
runtime: sp=0x1896c6861390 stack=[0x1896c6860000, 0x1896c6960000]
fatal error: stack overflow
...
goroutine 1 gp=0x46d140ea000 m=0 mp=0x7ff6572bed80 [running]:
main.countDown(0xfffffffffffeac79?)
.../main.go:8 +0x2b fp=0x46d142e13a0 sp=0x46d142e1398 pc=0x7ff6571d524b
main.countDown(...)
...
The deferred function never runs. With the default 1 GB limit the program would use a lot of memory before crashing.
Practical consequences:
- recursion depth proportional to
log(n)(balanced trees, binary search, merge sort) is always fine - recursion depth proportional to
nis fine for thousands or even millions of levels, but every frame uses memory - if depth depends on untrusted input (deeply nested JSON from the network, a linked list of unknown length), limit the depth or use an explicit stack; a stack overflow can't be recovered
No tail call optimization
Some languages turn a call in tail position (return f(n-1)) into a jump, so tail-recursive functions run in constant stack space. The Go compiler doesn't do this. A tail-recursive function in Go uses one stack frame per call, just like any other recursive function. If you need a loop, write a loop.
Exponential recursion and memoization
The textbook Fibonacci definition translates directly to code, but it's extremely slow because it computes the same values over and over:
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 {
calls++
if n < 2 {
return n
}
if v, ok := memo[n]; ok {
return v
}
v := fibMemo(n-1, memo) + fibMemo(n-2, memo)
memo[n] = v
return v
}
func main() {
fmt.Println("fib(35) =", fib(35), "calls:", calls)
calls = 0
fmt.Println("fibMemo(35) =", fibMemo(35, map[int]int{}), "calls:", calls)
calls = 0
fmt.Println("fibMemo(90) =", fibMemo(90, map[int]int{}), "calls:", calls)
}
fib(35) = 9227465 calls: 29860703
fibMemo(35) = 9227465 calls: 69
fibMemo(90) = 2880067194370816120 calls: 179
fib(35) makes almost 30 million calls; the number of calls grows exponentially with n. Memoization (caching results of previous calls) reduces that to a linear number of calls. fib(90) without memoization would effectively never finish.
Memoization works when the function is pure: the same arguments always give the same result.
Recursive closures
A function literal can't refer to itself in a := declaration, because the variable isn't in scope until the statement ends:
fact := func(n int) int {
if n <= 1 {
return 1
}
return n * fact(n-1) // compile error: undefined: fact
}
Declare the variable first, then assign:
package main
import "fmt"
func main() {
// declare the variable first so the closure can refer to itself
var fact func(n int) int
fact = func(n int) int {
if n <= 1 {
return 1
}
return n * fact(n-1)
}
fmt.Println(fact(10))
// a closure that captures state from the enclosing function
memo := map[int]int{}
var fib func(n int) int
fib = func(n int) int {
if n < 2 {
return n
}
if v, ok := memo[n]; ok {
return v
}
memo[n] = fib(n-1) + fib(n-2)
return memo[n]
}
fmt.Println(fib(50), len(memo))
}
3628800
12586269025 49
Recursive closures are handy for helpers that need access to local state (memo above, or result slices in the backtracking examples below) without passing it as a parameter on every call. See Closures for more about how closures capture variables.
Mutual recursion
Functions can call each other recursively. Package-level functions can be declared in any order, so no forward declarations are needed:
package main
import "fmt"
func isEven(n uint) bool {
if n == 0 {
return true
}
return isOdd(n - 1)
}
func isOdd(n uint) bool {
if n == 0 {
return false
}
return isEven(n - 1)
}
func main() {
fmt.Println(isEven(10), isOdd(7), isEven(3))
}
true true false
Mutual recursion is common in recursive descent parsers, where e.g. parseExpr calls parseTerm, which calls parseFactor, which calls parseExpr again for parenthesized expressions.
Recursive data structures
A struct can't contain itself (it would have infinite size) but it can contain a pointer to itself, or a slice or map of itself. Operations on such structures are naturally recursive.
Here's a generic binary search tree. Methods are called on a possibly nil pointer receiver; handling nil inside the method gives a clean base case:
package main
import (
"cmp"
"fmt"
"iter"
)
type Tree[T cmp.Ordered] struct {
Left, Right *Tree[T]
Value T
}
// Insert returns the root of the tree with v added.
func (t *Tree[T]) Insert(v T) *Tree[T] {
if t == nil {
return &Tree[T]{Value: v}
}
if v < t.Value {
t.Left = t.Left.Insert(v)
} else {
t.Right = t.Right.Insert(v)
}
return t
}
func (t *Tree[T]) Height() int {
if t == nil {
return 0
}
return 1 + max(t.Left.Height(), t.Right.Height())
}
func (t *Tree[T]) Contains(v T) bool {
switch {
case t == nil:
return false
case v < t.Value:
return t.Left.Contains(v)
case v > t.Value:
return t.Right.Contains(v)
default:
return true
}
}
// All returns an iterator over values in sorted order.
func (t *Tree[T]) All() iter.Seq[T] {
return func(yield func(T) bool) {
t.push(yield)
}
}
// push returns false when the consumer stopped early.
func (t *Tree[T]) push(yield func(T) bool) bool {
if t == nil {
return true
}
return t.Left.push(yield) && yield(t.Value) && t.Right.push(yield)
}
func main() {
var root *Tree[int]
for _, v := range []int{50, 30, 70, 20, 40, 60, 80, 35} {
root = root.Insert(v)
}
fmt.Println("height:", root.Height())
fmt.Println("contains 35:", root.Contains(35), "contains 36:", root.Contains(36))
for v := range root.All() {
fmt.Print(v, " ")
}
fmt.Println()
for v := range root.All() {
if v > 40 {
break // push stops descending
}
fmt.Print(v, " ")
}
fmt.Println()
}
height: 4
contains 35: true contains 36: false
20 30 35 40 50 60 70 80
20 30 35 40
All returns an iter.Seq, so the tree works with for ... range. The recursive helper push returns false as soon as yield returns false (the loop executed break), which stops the whole traversal instead of visiting the remaining nodes. Calling yield again after it returned false panics, so propagating this result is required. See Generics for more on type parameters.
Walking nested data
Data decoded from JSON into any is a tree of map[string]any, []any and scalar values. A type switch plus recursion visits all of it:
package main
import (
"encoding/json"
"fmt"
"log"
"maps"
"slices"
)
// walk prints every leaf value with its path.
func walk(path string, v any) {
switch v := v.(type) {
case map[string]any:
// sort keys: map iteration order is random
for _, k := range slices.Sorted(maps.Keys(v)) {
walk(path+"."+k, v[k])
}
case []any:
for i, child := range v {
walk(fmt.Sprintf("%s[%d]", path, i), child)
}
default:
fmt.Printf("%s = %v\n", path, v)
}
}
func main() {
data := []byte(`{
"name": "server",
"ports": [80, 443],
"tls": {"enabled": true, "certs": [{"host": "a.com"}, {"host": "b.com"}]}
}`)
var v any
if err := json.Unmarshal(data, &v); err != nil {
log.Fatal(err)
}
walk("$", v)
}
$.name = server
$.ports[0] = 80
$.ports[1] = 443
$.tls.certs[0].host = a.com
$.tls.certs[1].host = b.com
$.tls.enabled = true
The same shape works for walking an AST, an HTML DOM or a directory tree. Here's a function that sums file sizes in a directory tree. It uses fs.FS, so it works with real directories (os.DirFS), embedded files and, in this example, an in-memory file system:
package main
import (
"fmt"
"io/fs"
"log"
"path"
"testing/fstest"
)
// dirSize returns the total size of all files under dir.
func dirSize(fsys fs.FS, dir string) (int64, error) {
entries, err := fs.ReadDir(fsys, dir)
if err != nil {
return 0, err
}
var total int64
for _, e := range entries {
p := path.Join(dir, e.Name())
if e.IsDir() {
n, err := dirSize(fsys, p)
if err != nil {
return 0, err
}
total += n
continue
}
info, err := e.Info()
if err != nil {
return 0, err
}
total += info.Size()
}
return total, nil
}
func main() {
fsys := fstest.MapFS{
"readme.md": {Data: make([]byte, 100)},
"src/main.go": {Data: make([]byte, 250)},
"src/util/str.go": {Data: make([]byte, 40)},
"src/util/str_test.go": {Data: make([]byte, 60)},
}
for _, dir := range []string{".", "src", "src/util"} {
n, err := dirSize(fsys, dir)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%-9s %d bytes\n", dir, n)
}
}
. 450 bytes
src 350 bytes
src/util 100 bytes
For real file systems the standard library already provides filepath.WalkDir and fs.WalkDir; see Directory operations.
Divide and conquer
Divide-and-conquer algorithms split the input, solve the parts recursively and combine the results. Merge sort and binary search are classic examples:
package main
import "fmt"
func mergeSort(s []int) []int {
if len(s) <= 1 {
return s
}
mid := len(s) / 2
left := mergeSort(s[:mid])
right := mergeSort(s[mid:])
return merge(left, right)
}
func merge(a, b []int) []int {
res := make([]int, 0, len(a)+len(b))
for len(a) > 0 && len(b) > 0 {
if a[0] <= b[0] {
res = append(res, a[0])
a = a[1:]
} else {
res = append(res, b[0])
b = b[1:]
}
}
res = append(res, a...)
return append(res, b...)
}
// binarySearch returns the index of x in sorted s, or -1.
func binarySearch(s []int, x int) int {
return search(s, x, 0, len(s)-1)
}
func search(s []int, x, lo, hi int) int {
if lo > hi {
return -1
}
mid := lo + (hi-lo)/2
switch {
case s[mid] < x:
return search(s, x, mid+1, hi)
case s[mid] > x:
return search(s, x, lo, mid-1)
default:
return mid
}
}
func main() {
s := mergeSort([]int{38, 27, 43, 3, 9, 82, 10})
fmt.Println(s)
fmt.Println(binarySearch(s, 43), binarySearch(s, 5))
}
[3 9 10 27 38 43 82]
5 -1
Both recurse to a depth of about log2(n), so even a billion elements need only ~30 levels. In real code use slices.Sort and slices.BinarySearch; the recursive versions are shown here because they're easy to follow.
Backtracking
Backtracking explores a tree of choices: make a choice, recurse, then undo the choice and try the next one. It's used for permutations, combinations, puzzles (sudoku, n-queens) and constraint searches.
package main
import "fmt"
func permutations(items []string) [][]string {
var res [][]string
var current []string
used := make([]bool, len(items))
var backtrack func()
backtrack = func() {
if len(current) == len(items) {
res = append(res, append([]string(nil), current...)) // copy!
return
}
for i, it := range items {
if used[i] {
continue
}
used[i] = true
current = append(current, it)
backtrack()
current = current[:len(current)-1] // undo
used[i] = false
}
}
backtrack()
return res
}
// subsetSums finds all subsets of nums that add up to target.
func subsetSums(nums []int, target int) [][]int {
var res [][]int
var rec func(start, remaining int, chosen []int)
rec = func(start, remaining int, chosen []int) {
if remaining == 0 {
res = append(res, append([]int(nil), chosen...))
return
}
for i := start; i < len(nums); i++ {
if nums[i] > remaining {
continue // prune
}
rec(i+1, remaining-nums[i], append(chosen, nums[i]))
}
}
rec(0, target, nil)
return res
}
func main() {
for _, p := range permutations([]string{"a", "b", "c"}) {
fmt.Println(p)
}
fmt.Println(subsetSums([]int{2, 3, 5, 7, 8}, 10))
}
[a b c]
[a c b]
[b a c]
[b c a]
[c a b]
[c b a]
[[2 3 5] [2 8] [3 7]]
Two things to watch for:
- copy the result before storing it.
currentis reused and modified after a solution is found, so storing it directly would leave every entry sharing the same backing array - prune branches that can't lead to a solution (
nums[i] > remaining); it can shrink the search space dramatically
In subsetSums, append(chosen, nums[i]) may write into a backing array shared between sibling calls. That's safe here because each call only overwrites a slot that earlier siblings no longer need, and results are copied before being stored.
Converting recursion to iteration
Any recursion can be rewritten as a loop with an explicit stack (a slice). Do this when depth depends on untrusted input, or when you need to pause and resume the traversal.
package main
import "fmt"
type Tree struct {
Name string
Children []*Tree
}
// printRec prints the tree depth-first using recursion.
func printRec(t *Tree, depth int) {
fmt.Printf("%*s%s\n", depth*2, "", t.Name)
for _, c := range t.Children {
printRec(c, depth+1)
}
}
// printIter does the same with an explicit stack.
func printIter(root *Tree) {
type item struct {
t *Tree
depth int
}
stack := []item{{root, 0}}
for len(stack) > 0 {
it := stack[len(stack)-1]
stack = stack[:len(stack)-1]
fmt.Printf("%*s%s\n", it.depth*2, "", it.t.Name)
// push children in reverse so the first child is processed first
for i := len(it.t.Children) - 1; i >= 0; i-- {
stack = append(stack, item{it.t.Children[i], it.depth + 1})
}
}
}
func main() {
root := &Tree{Name: "src", Children: []*Tree{
{Name: "cmd", Children: []*Tree{{Name: "main.go"}}},
{Name: "internal", Children: []*Tree{
{Name: "db", Children: []*Tree{{Name: "db.go"}}},
{Name: "util.go"},
}},
{Name: "go.mod"},
}}
printRec(root, 0)
fmt.Println("---")
printIter(root)
}
src
cmd
main.go
internal
db
db.go
util.go
go.mod
---
src
cmd
main.go
internal
db
db.go
util.go
go.mod
The iterative version is longer, and children must be pushed in reverse order to produce the same output. Use recursion by default; switch to an explicit stack when you have a reason to.
Simple linear recursion, like summing a linked list, should just be a for loop.
Parallel recursion
Divide-and-conquer recursion parallelizes well because subproblems are independent. Starting a goroutine for every call would be wasteful, so stop spawning below a size cutoff:
package main
import (
"fmt"
"math/rand/v2"
"slices"
"sync"
)
const cutoff = 2048 // below this size, sort sequentially
func parallelMergeSort(s []int) []int {
if len(s) <= cutoff {
return slices.Sorted(slices.Values(s))
}
mid := len(s) / 2
var left, right []int
var wg sync.WaitGroup
wg.Go(func() { left = parallelMergeSort(s[:mid]) })
right = parallelMergeSort(s[mid:]) // reuse the current goroutine
wg.Wait()
return merge(left, right)
}
func merge(a, b []int) []int {
res := make([]int, 0, len(a)+len(b))
for len(a) > 0 && len(b) > 0 {
if a[0] <= b[0] {
res = append(res, a[0])
a = a[1:]
} else {
res = append(res, b[0])
b = b[1:]
}
}
res = append(res, a...)
return append(res, b...)
}
func main() {
s := make([]int, 1_000_000)
for i := range s {
s[i] = rand.IntN(1_000_000)
}
sorted := parallelMergeSort(s)
fmt.Println(len(sorted), slices.IsSorted(sorted))
}
1000000 true
Notes:
sync.WaitGroup.Go(Go 1.25+) starts a goroutine and handlesAddandDonefor you- only one half runs in a new goroutine; the current goroutine sorts the other half instead of just waiting
- each goroutine writes to its own variable (
left), andwg.Waitmakes that write visible, so no mutex is needed - the cutoff keeps the number of goroutines proportional to
n / cutoff; benchmark to pick a good value (see Benchmarks)
Summary
- a recursive function needs a base case and a recursive case that makes progress toward it
- goroutine stacks grow automatically, so deep recursion works, but there is a limit (1 GB by default) and exceeding it is a fatal error that
recovercan't catch - Go doesn't optimize tail calls; use loops for simple linear recursion
- memoize pure functions that recompute the same subproblems
- declare the variable before assigning a recursive closure to it:
var f func(int) int; f = func... - handle
nilreceivers to get clean base cases in methods of recursive types - recursive
iter.Seqiterators must stop whenyieldreturnsfalse - copy reused slices when storing results in backtracking
- use an explicit stack when depth is controlled by untrusted input
- parallelize divide-and-conquer recursion with goroutines, but only above a size cutoff