Go recursion programs solve a problem by having a function call itself on a smaller version of the same problem. Recursion makes some tasks, like Tower of Hanoi, tree walks and subsets, much shorter than loops. In this post, you will write fourteen recursion programs with their exact output, and then practice the recursion questions interviewers use to test your thinking.
This post builds on our Go function programs, since recursion is just a function calling itself. We also redo some loops from our Go loop programs the recursive way, so you can compare both styles. All programs were tested on Go 1.27.
What are Go Recursion Programs?
Go recursion programs use a function that calls itself. Every recursive function needs two parts: a base case that stops the calls, and a recursive case that moves closer to the base case each time.
Think of a set of Russian dolls. To reach the smallest doll, you open one doll, then open the doll inside it, and so on. You stop when a doll does not open. That last doll is the base case.
Why Go Recursion Programs Matter
Some problems have a shape that repeats inside itself. For example, a folder contains folders, a tree has smaller trees and a maths formula like factorial is defined using itself. Go recursion programs let you write these problems almost exactly as you would describe them.
- Trees and folders: walking nested data is natural with recursion.
- Divide and conquer: merge sort and quick sort are recursive.
- Interviews: factorial, Fibonacci, Hanoi and subsets are classic questions.
How Go Recursion Programs Work
Each call gets its own copy of the parameters and local variables on the call stack. The calls stack up until one hits the base case. Then the results flow back down, one call at a time, until the first call returns the final answer.

The table below shows the base case and recursive case for each program in this post.
| Problem | Base case | Recursive case |
|---|---|---|
| Factorial | n <= 1 returns 1 | n * fact(n-1) |
| Fibonacci | n < 2 returns n | fib(n-1) + fib(n-2) |
| Power | exp == 0 returns 1 | base * pow(base, exp-1) |
| GCD | b == 0 returns a | gcd(b, a % b) |
| Sum of digits | n == 0 returns 0 | n%10 + sum(n/10) |
| Reverse string | len 0 or 1 | reverse(rest) + first |
Classic Go Recursion Programs
These first Go recursion programs are the ones every interviewer expects you to know. If recursion is new to you, start with the two easy warm-ups in Program 1 and Program 2.
Program 1: Say Hello a Few Times
This is the smallest recursive function you can write. It prints a message, then calls itself with one less to go.
package main
import "fmt"
// sayHello prints "Hello" the given number of times, using recursion.
func sayHello(times int) {
// Base case: nothing left to print, so stop.
if times == 0 {
return
}
fmt.Println("Hello, times left:", times)
// Recursive case: call itself with a smaller number.
sayHello(times - 1)
}
func main() {
sayHello(3)
}
Hello, times left: 3
Hello, times left: 2
Hello, times left: 1
The first call gets 3, prints a line and then calls sayHello(2). Each new call gets a smaller number. When the number reaches 0, the base case returns and the calls stop. Without that if, the function would call itself forever.
Program 2: Add the Numbers from 1 to N
package main
import "fmt"
// sumUpTo returns 1 + 2 + ... + number.
func sumUpTo(number int) int {
// Base case: the sum up to 0 is 0.
if number == 0 {
return 0
}
// Recursive case: this number plus the sum of all smaller numbers.
return number + sumUpTo(number-1)
}
func main() {
fmt.Println(sumUpTo(5))
fmt.Println(sumUpTo(10))
}
15
55
sumUpTo(5) asks for 5 plus sumUpTo(4), which asks for 4 plus sumUpTo(3), and so on. At 0, the base case gives back 0. Then each waiting call adds its own number, so you get 1 + 2 + 3 + 4 + 5 = 15.
Program 3: Factorial
package main
import "fmt"
// factorial returns number x (number-1) x ... x 1.
func factorial(number int) int {
if number <= 1 {
return 1 // base case
}
return number * factorial(number-1) // recursive case
}
func main() {
for _, number := range []int{0, 1, 5, 10} { // range gives each index (ignored with _) and value
fmt.Printf("%d! = %d\n", number, factorial(number)) // %d prints a whole number
}
}
0! = 1
1! = 1
5! = 120
10! = 3628800
This has the same shape as Program 2, but it multiplies instead of adds. factorial(5) becomes 5 x factorial(4), and so on, until factorial(1) returns 1. Then the multiplications finish on the way back.
Program 4: Fibonacci, Plain and Memoized
The plain version is short but slow, because it repeats the same work many times. A memo map stores answers we already know.
package main
import "fmt"
// fib returns the Fibonacci number at the given position, the slow way.
func fib(position int) int {
if position < 2 {
return position // base case: fib(0) is 0, fib(1) is 1
}
return fib(position-1) + fib(position-2)
}
// fibMemo does the same, but saves each answer in memo so it is worked out once.
func fibMemo(position int, memo map[int]int) int {
if position < 2 {
return position
}
// Step 1: if we already know the answer, return it. ok is true if the key was found.
value, ok := memo[position]
if ok {
return value
}
// Step 2: work it out once and save it in the map.
memo[position] = fibMemo(position-1, memo) + fibMemo(position-2, memo)
return memo[position]
}
func main() {
fmt.Println(fib(10))
fmt.Println(fibMemo(80, map[int]int{})) // map[int]int{} is a new empty map
}
55
23416728348467685
Both functions use the rule “add the two numbers before”. The memo version checks the map first and only does the work for new positions. Plain fib(80) would take a very long time, because it makes billions of calls. With memoization, each number is worked out once, so fibMemo(80) is instant.
Program 5: Power with Fast Exponent
package main
import "fmt"
// power returns base multiplied by itself exponent times.
func power(base, exponent int) int {
// Base case: anything to the power 0 is 1.
if exponent == 0 {
return 1
}
// Step 1: work out the answer for half the exponent.
half := power(base, exponent/2)
// Step 2: square it. If the exponent is odd, multiply by base once more.
if exponent%2 == 0 { // % gives the remainder, so 0 means even
return half * half
}
return half * half * base
}
func main() {
fmt.Println(power(2, 10), power(3, 5), power(7, 0))
}
1024 243 1
The idea is that 2 to the 10 equals (2 to the 5) times (2 to the 5). So each call halves the exponent instead of taking one step down. As a result, power(2, 10) needs only about 4 calls, not 10.
Program 6: GCD with Euclid’s Method
package main
import "fmt"
// gcd returns the greatest common divisor of first and second.
func gcd(first, second int) int {
// Base case: when second is 0, first is the answer.
if second == 0 {
return first
}
// Recursive case: the GCD stays the same if we use second and the remainder.
return gcd(second, first%second)
}
func main() {
fmt.Println(gcd(48, 180), gcd(17, 5), gcd(100, 75))
}
12 1 25
Each call swaps in the remainder, so the numbers shrink fast. When the remainder becomes 0, the other number is the GCD. This is the recursive form of the loop in our Go number programs. Both give the same answers.
Digit and String Go Recursion Programs
These Go recursion programs break numbers and strings into smaller pieces.
Program 7: Sum of Digits
package main
import "fmt"
// digitSum adds up all the digits of number.
func digitSum(number int) int {
if number == 0 {
return 0 // base case: no digits left
}
lastDigit := number % 10 // 98765 % 10 is 5
rest := number / 10 // 98765 / 10 is 9876
return lastDigit + digitSum(rest)
}
func main() {
fmt.Println(digitSum(98765), digitSum(7), digitSum(0))
}
35 7 0
% 10 gives the last digit, and / 10 drops it. Each call keeps one digit and passes the rest on. When nothing is left, the base case returns 0, and the digits add up on the way back.
Program 8: Reverse a String
package main
import "fmt"
// reverse returns the letters in the opposite order.
func reverse(letters []rune) string { // a rune is one character
// Base case: zero or one letter is already reversed.
if len(letters) <= 1 {
return string(letters)
}
// Reverse everything after the first letter, then put the first letter last.
// letters[1:] means "from index 1 to the end".
return reverse(letters[1:]) + string(letters[0])
}
func main() {
fmt.Println(reverse([]rune("golang"))) // []rune(...) splits a string into characters
fmt.Println(reverse([]rune("चाय")))
}
gnalog
याच
We take the first rune off, reverse the rest, and add the first rune at the end. Working with runes keeps each letter whole, though Hindi vowel signs may still look odd once moved.
Program 9: Palindrome Check
package main
import "fmt"
// isPalindrome reports whether word reads the same forwards and backwards.
func isPalindrome(word string) bool {
// Base case: zero or one letter is always a palindrome.
if len(word) <= 1 {
return true
}
// Step 1: the first and last letters must match.
if word[0] != word[len(word)-1] {
return false
}
// Step 2: check the middle part, without the first and last letters.
return isPalindrome(word[1 : len(word)-1])
}
func main() {
for _, word := range []string{"racecar", "level", "golang", "a"} {
fmt.Println(word, isPalindrome(word))
}
}
racecar true
level true
golang false
a true
Each call compares the outer two letters and then checks the inside. For “racecar”, it checks r and r, then a and a, then c and c, and stops at “e”. This byte version is fine for plain English words.
Program 10: Decimal to Binary
package main
import (
"fmt"
"strconv"
)
// toBinary turns a whole number into a string of 0s and 1s.
func toBinary(number int) string {
// Base case: 0 and 1 are the same in binary.
if number < 2 {
return strconv.Itoa(number) // Itoa turns an int into a string
}
// The higher bits come from number/2, and the last bit is number%2.
return toBinary(number/2) + strconv.Itoa(number%2)
}
func main() {
fmt.Println(toBinary(13), toBinary(45), toBinary(0))
}
1101 101101 0
Dividing by 2 drops the last binary digit, and % 2 tells you what that digit was. The recursive call builds the higher bits first, so the digits come out in the right order without reversing.
Advanced Go Recursion Programs
These Go recursion programs solve problems that are hard to write with a simple loop.
Program 11: Tower of Hanoi
Move all disks from peg A to peg C, one at a time, never putting a bigger disk on a smaller one.
package main
import "fmt"
// moves counts every move. It sits outside the function so all calls share it.
var moves int
// hanoi moves the top "disks" disks from one peg to another, using a spare peg.
func hanoi(disks int, from, to, spare string) {
if disks == 0 {
return // base case: no disks to move
}
// Step 1: move the smaller disks out of the way, onto the spare peg.
hanoi(disks-1, from, spare, to)
// Step 2: move the biggest disk of this group to its target.
moves++
fmt.Printf("Move disk %d from %s to %s\n", disks, from, to)
// Step 3: move the smaller disks back on top of it.
hanoi(disks-1, spare, to, from)
}
func main() {
hanoi(3, "A", "C", "B")
fmt.Println("Total moves:", moves)
}
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
Total moves: 7
To move 3 disks, move the top 2 out of the way, move the big disk, then move the 2 back on top. Moving 2 disks uses the same three steps with 1 disk. The total is always 2 to the power n, minus 1.
Program 12: Sum of a Slice
package main
import "fmt"
// sum adds up all the numbers in the slice.
func sum(numbers []int) int {
if len(numbers) == 0 {
return 0 // base case: an empty slice adds up to 0
}
// The first number plus the sum of the rest.
return numbers[0] + sum(numbers[1:])
}
func main() {
fmt.Println(sum([]int{4, 8, 15, 16, 23, 42}))
}
108
Each call takes the first number and passes the rest of the slice on. The slice gets one item shorter on every call. When it is empty, the base case returns 0 and the numbers add up.
Program 13: All Subsets (Power Set)
package main
import "fmt"
// subsets builds every subset of items and saves each one into results.
func subsets(items []string, index int, current []string, results *[][]string) {
// Base case: every item has been decided, so save a copy of current.
if index == len(items) {
saved := append([]string{}, current...) // copy current into a new slice
*results = append(*results, saved) // *results is the slice the pointer points to
return
}
// Choice 1: skip this item.
subsets(items, index+1, current, results)
// Choice 2: take this item.
withItem := append(current, items[index])
subsets(items, index+1, withItem, results)
}
func main() {
var result [][]string
subsets([]string{"a", "b", "c"}, 0, nil, &result) // &result passes the address, so subsets can add to it
fmt.Println(len(result), result)
}
8 [[] [c] [b] [b c] [a] [a c] [a b] [a b c]]
For each item, we make two choices: skip it or take it. With 3 items, that gives 2 x 2 x 2 = 8 subsets. We copy current before saving it, so later changes do not affect saved results.
Program 14: Walk a Nested Menu (Tree)
package main
import (
"fmt"
"strings"
)
// Menu is one menu item that can hold smaller menu items inside it.
type Menu struct {
Name string
Children []Menu
}
// printMenu prints a menu and all its children, indented by depth.
func printMenu(menu Menu, depth int) {
// strings.Repeat adds two spaces for each level of depth.
fmt.Println(strings.Repeat(" ", depth) + "- " + menu.Name)
for _, child := range menu.Children {
printMenu(child, depth+1) // each child is printed one level deeper
}
}
func main() {
root := Menu{"Shop", []Menu{
{"Men", []Menu{{"Shirts", nil}, {"Shoes", nil}}}, // nil means "no children"
{"Women", []Menu{{"Dresses", nil}}},
{"Sale", nil},
}}
printMenu(root, 0)
}
- Shop
- Men
- Shirts
- Shoes
- Women
- Dresses
- Sale
The function prints its own name, then calls itself for every child with a bigger indent. There is no explicit base case here. The recursion stops naturally when a menu has no children, because the loop has nothing to visit.
Recursion vs Loops in Go Recursion Programs
Most Go recursion programs can also be written with a loop. The diagram and table below compare the two.

| Feature | Recursion | Loop |
|---|---|---|
| Code for trees and nested data | Short and clear | Needs your own stack |
| Memory | One stack frame per call | Constant |
| Speed | Slower, call overhead | Faster |
| Risk | Stack overflow if too deep | Endless loop if wrong |
| Best for | Trees, Hanoi, subsets, sorts | Counting, sums, simple sequences |
So use recursion when the problem is naturally nested. Use a loop for simple counting, because it is faster and uses less memory.
Common Mistakes in Go Recursion Programs
- No base case: the function calls itself forever and crashes with a stack overflow.
- Not moving toward the base case:
fact(n)callingfact(n)never stops. - Plain recursive Fibonacci for big n: it repeats work, so add a memo or use a loop.
- Sharing a slice in results: in subset problems, copy the current slice before saving it.
- Expecting tail call optimisation: Go does not do it, so very deep recursion still uses stack.
Best Practices for Go Recursion Programs
- Write the base case first, before the recursive call.
- Make each call smaller, so the base case is always reached.
- Memoize repeated sub-problems with a map.
- Prefer a loop when the recursion is just a straight line, like a sum.
- Test the smallest inputs, such as 0, 1 and an empty slice.
Go Recursion Programs Interview Questions and Answers
Interviewers use short Go recursion programs to test how recursion behaves. Each program is complete, with real output from Go 1.27.
Go Recursion Programs Concept Questions
Q1. What are the two parts of every recursive function?
A base case that returns without calling itself, and a recursive case that calls itself with a smaller input. Without a base case, the function never stops.
Q2. How many calls does plain fib(10) make?
package main
import "fmt"
// calls counts how many times fib runs.
var calls int
// fib returns the Fibonacci number at position and counts every call.
func fib(position int) int {
calls++
if position < 2 {
return position
}
return fib(position-1) + fib(position-2)
}
func main() {
fmt.Println(fib(10), calls)
}
55 177
177 calls for such a small number shows how much work is repeated. The number of calls grows exponentially, which is why memoization matters.
Q3. What happens when recursion never stops in Go?
The goroutine stack keeps growing until it hits Go’s limit, which is about 1 GB on 64-bit systems. Then the program crashes with “fatal error: stack overflow”. Go stacks grow on demand, so you get much deeper than in many languages before this happens.
Q4. Does Go optimise tail recursion?
No. A tail call still adds a new stack frame. So for very deep problems, rewrite the recursion as a loop.
Output Questions
Q5. What does this program print?
package main
import "fmt"
// countDown prints number, number-1, ... 1 and then "Go!".
func countDown(number int) {
if number == 0 {
fmt.Println("Go!")
return
}
fmt.Print(number, " ") // print first, then call
countDown(number - 1)
}
func main() {
countDown(5)
}
5 4 3 2 1 Go!
Each call prints its number before it calls itself. So the numbers come out from 5 down to 1, and the base case prints “Go!”.
Q6. What does this program print?
package main
import "fmt"
// show prints the numbers from 1 up to number.
func show(number int) {
if number == 0 {
return
}
show(number - 1) // call first
fmt.Print(number, " ") // print after the smaller call has finished
}
func main() {
show(4)
fmt.Println()
}
1 2 3 4
The print comes after the recursive call. So the deepest call prints first, and the numbers come out in increasing order. Moving the print before the call would reverse the order.
Q7. What does this program print?
package main
import "fmt"
// isEven says number is even if number-1 is odd.
func isEven(number int) bool {
if number == 0 {
return true
}
return isOdd(number - 1)
}
// isOdd says number is odd if number-1 is even.
func isOdd(number int) bool {
if number == 0 {
return false
}
return isEven(number - 1)
}
func main() {
fmt.Println(isEven(10), isOdd(7), isEven(3))
}
true true false
This is mutual recursion: two functions that call each other. Go allows it because functions in a package can call each other in any order.
Q8. What does this program print?
package main
import "fmt"
// count returns how many steps of 2 it takes to reach 0 or below.
func count(number int) int {
if number <= 0 {
return 0
}
return 1 + count(number-2)
}
func main() {
fmt.Println(count(7), count(8))
}
4 4
For 7, the calls go 7, 5, 3, 1, which is 4 calls before reaching zero or below. For 8, they go 8, 6, 4, 2, which is also 4.
Q9. How would you print a number’s digits in order with recursion?
package main
import "fmt"
// printDigits prints each digit of number from left to right.
func printDigits(number int) {
if number >= 10 {
printDigits(number / 10) // print the higher digits first
}
fmt.Print(number%10, " ") // then print the last digit
}
func main() {
printDigits(4096)
fmt.Println()
}
4 0 9 6
The recursive call handles the higher digits first, then the current call prints its own last digit.
Q10. What does this program print?
package main
import "fmt"
// depth counts the items in levels, one per call.
func depth(levels []string) int {
if len(levels) == 0 {
return 0
}
return 1 + depth(levels[1:]) // levels[1:] drops the first item
}
func main() {
fmt.Println(depth([]string{"root", "dir", "subdir", "file"}))
}
4
Each call drops one item and adds 1. When the slice is empty, the base case returns 0, so the answer is the number of items.
Q11. When should you choose recursion over a loop?
Choose recursion for naturally nested problems like trees, file systems, JSON documents and divide and conquer sorts. Choose a loop for straight sequences like sums, counts and simple series.
Q12. What is memoization?
It means saving the result of each call in a map or slice, so the same input is never worked out twice. It turns plain recursive Fibonacci from exponential time into linear time.
Practice Task
Staircase counting is one of the best-known Go recursion programs. Write a recursive function that counts how many ways you can climb a staircase of n steps if you can take 1 or 2 steps at a time. Print the answer for n = 1 to 10. Hint: the answer for n is the answer for n-1 plus the answer for n-2, so add a memo map.
Official Resources
Quick Recap
- Go recursion programs need a base case and a recursive case that moves toward it.
- Each call gets its own stack frame, and results return in reverse order.
- Memoization with a map stops plain Fibonacci from repeating work.
- Go does not optimise tail calls, so very deep recursion should become a loop.
- Recursion shines for trees, Hanoi, subsets and divide and conquer.
What’s Next?
Next, we group related data together. Read Go struct programs with output, with employee records, methods and embedding. To revise sorting, which uses recursion in merge and quick sort, see our Go sorting programs.


