Sub topic 12
Recursion
Recursion is when a function calls itself. This chapter assumes you can define functions with typed parameters, write if/else expressions, and run programs with cargo run. It covers the working model of recursion in Rust and the errors you will most often meet.
The working model
A recursive function has two parts:
- A base case that returns a value without calling the function again.
- A recursive case that calls the function with a smaller input, moving toward the base case.
Here is a factorial function. The factorial of n is n * (n - 1) * ... * 1.
fn factorial(n: u64) -> u64 {
if n <= 1 {
1
} else {
n * factorial(n - 1)
}
}
fn main() {
println!("{}", factorial(5));
}The program prints 120. The if/else is an expression, so each branch produces a u64 and the whole if is the function's return value. The base case is n <= 1. Each call passes n - 1, so the input shrinks until it reaches the base case.
How the calls unfold
Each call gets its own stack frame, a block of memory holding that call's parameters and local variables. The multiplication n * factorial(n - 1) cannot finish until the inner call returns, so the frames pile up and then resolve in reverse order.
Common errors
Missing or unreachable base case
If the base case is never reached, the calls never stop. The stack runs out of space and the program aborts with a stack overflow. Rust does not catch this at compile time. Check that every recursive call moves toward the base case.
Integer overflow
factorial(21) does not fit in a u64. In a debug build (cargo run), the multiplication panics with "attempt to multiply with overflow". In a release build (cargo run --release), the value silently wraps around. If large inputs are possible, use checked_mul, which returns an Option, or a wider type such as u128.
Unsigned subtraction
With an unsigned type such as u64, n - 1 panics in debug builds when n is 0. The n <= 1 check above avoids this. A base case written as n == 1 would break for input 0: the call would compute 0 - 1 and panic.
Return type omitted
Recursive functions need an explicit return type. Rust does not infer function signatures, so write -> u64 even though the body seems to make it obvious.
Recursion depth
Rust does not guarantee tail-call optimization. A tail call is a recursive call that is the very last thing a function does. Even if the compiler sometimes turns one into a loop, you cannot rely on it. Deep recursion, such as 100,000 levels, can overflow the stack of the main thread, which is typically a few megabytes.
When the depth depends on user input, prefer a loop:
fn factorial_iter(n: u64) -> u64 {
let mut result = 1;
for i in 2..=n {
result *= i;
}
result
}
fn main() {
println!("{}", factorial_iter(5));
}This uses constant stack space. Recursion remains a good fit when the problem is naturally nested, such as walking a tree or a directory structure, where the depth is small and the code reads more clearly.
| Approach | Stack use | Best for |
|---|---|---|
| Recursion | Grows with depth | Nested data, divide and conquer |
| Loop | Constant | Flat repetition, unbounded input sizes |
Mutual recursion
Two functions can call each other. Rust lets you define functions in any order within a module, so no forward declaration is needed.
fn is_even(n: u32) -> bool {
if n == 0 { true } else { is_odd(n - 1) }
}
fn is_odd(n: u32) -> bool {
if n == 0 { false } else { is_even(n - 1) }
}
fn main() {
println!("{}", is_even(10));
println!("{}", is_odd(7));
}Both calls print true. Each call reduces n by one, and n == 0 is the base case in both functions.
Exercise
What happens if you write fn countdown(n: u32) { println!("{n}"); countdown(n - 1); } with no base case and call countdown(3)?
Show answer
It prints 3, 2, 1, 0, and then n - 1 underflows on the unsigned u32, so a debug build panics with "attempt to subtract with overflow". Without the underflow check (release build), the value wraps to a huge number and the calls continue until the stack overflows. Either way, a base case such as if n == 0 { return; } is needed.
Exercise
Write a recursive function sum_to(n: u32) -> u32 that returns 1 + 2 + ... + n, with sum_to(0) returning 0.
Show answer
fn sumto(n: u32) -> u32 { if n == 0 { 0 } else { n + sumto(n - 1) } }