← Back to Go Course | Chapter 4: Functions | Lesson 7 of 7

Recursion

Recursion is when a function solves a big problem by asking a slightly smaller copy of itself for help, again and again, until the problem is small enough to answer directly.

A Basic Recursive Function

A recursive function calls itself, typically with a smaller or simpler input each time, until it reaches a base case that can be answered directly without further recursion. Factorial is the classic first example.

Example: A Basic Recursive Function

markup
package main

import "fmt"

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

func main() {
	fmt.Println(factorial(5))
}

The Importance of a Base Case

Without a base case that stops the recursion, a recursive function calls itself forever (until the program crashes from stack exhaustion). The base case is what turns an infinite chain of calls into a function that actually terminates.

Note: Always verify the recursive argument moves toward the base case on every call.

Example: The Importance of a Base Case

markup
package main

import "fmt"

func countdown(n int) {
	if n <= 0 {
		fmt.Println("liftoff!")
		return
	}
	fmt.Println(n)
	countdown(n - 1)
}

func main() {
	countdown(3)
}

Recursion on Recursive Data

Recursion is especially natural for data that is itself recursively structured, like computing the sum of a slice by adding its first element to the sum of the rest -- each recursive call handles one smaller piece of the same shape of problem.

Example: Recursion on Recursive Data

markup
package main

import "fmt"

func sumSlice(nums []int) int {
	if len(nums) == 0 {
		return 0
	}
	return nums[0] + sumSlice(nums[1:])
}

func main() {
	fmt.Println(sumSlice([]int{1, 2, 3, 4, 5}))
}
Common Mistakes
  1. Forgetting a base case, causing infinite recursion until the program crashes with a stack overflow.
  2. Writing recursive Fibonacci or similar without memoization, causing exponential recomputation for larger inputs.
  3. Assuming Go automatically optimizes tail-recursive calls like some functional languages -- it does not, so deep recursion still consumes stack space.
Chapter Summary
  • A recursive function calls itself with a smaller version of the original problem.
  • Every recursive function needs a base case that stops the recursion.
  • Go does not perform tail-call optimization, so very deep recursion can exhaust the stack.
  • Recursion is a natural fit for problems with a naturally recursive structure, like tree traversal.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.