Sub topic 12
Recursion
Recursion is when a function calls itself, directly or through other functions. This chapter assumes you can define functions with typed parameters and return values, write if/else expressions, and run programs with cargo. It covers how to structure a recursive function, what happens on the call stack, and the limits Rust places on the technique in practice.
The two parts of a recursive function
Every working recursive function has two parts:
- A base case. This is an input for which the function returns a value without calling itself.
- A recursive case. The function calls itself with an input that is closer to the base case.
If either part is missing, the function never finishes. Here is the factorial function, where n! is the product of the integers from 1 to n.
fn factorial(n: u64) -> u64 {
if n <= 1 {
1
} else {
n * factorial(n - 1)
}
}
fn main() {
println!("{}", factorial(5));
}This prints 120. The base case is n <= 1, which returns 1. The recursive case multiplies n by the factorial of n - 1. Because if/else is an expression, each branch produces a u64 and the whole if is the function's return value. No return keyword is needed.
The base case uses <= rather than == 1. With n == 1, calling factorial(0) would compute 0 * factorial(u64::MAX) because 0 - 1 on an unsigned integer overflows. In a debug build that panics, and in a release build it wraps and recurses almost forever. Using <= makes factorial(0) return 1, which is also the mathematically correct answer.
What happens on the call stack
Each call to a function gets its own stack frame. A frame holds the function's parameters, local variables, and the address to return to. A recursive call pushes a new frame, and the frame is removed when that call returns.
The following diagram shows the calls for factorial(3).
The multiplication happens after the inner call returns. That is why factorial(3) must keep its frame alive while factorial(2) runs. At the deepest point, three factorial frames exist at once. For input n, the depth is n, so memory use grows linearly with the input.
Stack overflow
The stack has a fixed size. On most platforms the main thread's stack is a few megabytes (commonly 8 MiB on Linux, 1 MiB on Windows). Threads created with std::thread::spawn default to 2 MiB. If recursion goes deep enough to use it all, the program aborts with a stack overflow.
fn count_down(n: u64) -> u64 {
if n == 0 {
0
} else {
1 + count_down(n - 1)
}
}
fn main() {
println!("{}", count_down(100));
// count_down(100_000_000) would likely overflow the stack.
}A stack overflow in Rust is not a normal panic. The runtime prints a message such as thread 'main' has overflowed its stack and aborts the process. You cannot catch it with std::panic::catch_unwind.
Frame size depends on the function, the optimization level, and the target. A debug build usually uses larger frames than a release build, so a depth that works in --release can overflow in a debug build.
Rust does not guarantee tail-call optimization
A tail call is a call that is the very last action of a function, so its result is returned unchanged. Some languages turn tail calls into jumps, which keeps the stack flat. Rust does not guarantee this. LLVM, the compiler backend, sometimes performs the optimization in release builds, but you cannot rely on it, and it does not happen in debug builds.
You can still write the function in an accumulator style, which makes the recursive call the last operation.
fn factorial_acc(n: u64, acc: u64) -> u64 {
if n <= 1 {
acc
} else {
factorial_acc(n - 1, acc * n)
}
}
fn main() {
println!("{}", factorial_acc(5, 1));
}This form is tail-recursive in shape, but the stack may still grow. If depth matters, convert it to a loop, which is guaranteed to use constant stack space.
fn factorial_loop(n: u64) -> u64 {
let mut acc = 1;
let mut i = 2;
while i <= n {
acc *= i;
i += 1;
}
acc
}
fn main() {
println!("{}", factorial_loop(5));
}Integer overflow is the usual limit
For factorial, the stack is rarely the first thing to break. u64 overflows at 21!. In a debug build, factorial(21) panics with "attempt to multiply with overflow". In a release build the default is to wrap silently, which gives a wrong answer. If you need to detect this in every build, use checked_mul, which returns an Option.
fn checked_factorial(n: u64) -> Option<u64> {
if n <= 1 {
Some(1)
} else {
n.checked_mul(checked_factorial(n - 1)?)
}
}
fn main() {
println!("{:?}", checked_factorial(20));
println!("{:?}", checked_factorial(21));
}The first line prints Some(2432902008176640000) and the second prints None. The ? operator returns None from the current call as soon as an inner call fails, so the failure propagates up through every frame.
Recursion over branching data
Recursion fits best when the data is itself recursive, such as a tree. Here a match on an enum selects the base case and the recursive case. The enum needs Box because a type cannot contain itself directly without a known size.
enum Tree {
Leaf(i32),
Node(Box<Tree>, Box<Tree>),
}
fn sum(tree: &Tree) -> i32 {
match tree {
Tree::Leaf(value) => *value,
Tree::Node(left, right) => sum(left) + sum(right),
}
}
fn main() {
let tree = Tree::Node(
Box::new(Tree::Leaf(1)),
Box::new(Tree::Node(
Box::new(Tree::Leaf(2)),
Box::new(Tree::Leaf(3)),
)),
);
println!("{}", sum(&tree));
}This prints 6. The function takes &Tree, so the caller keeps ownership. Tree::Leaf is the base case, and Tree::Node is the recursive case with two calls. Here the depth equals the height of the tree, not its size, so a balanced tree with a million leaves needs only about 20 frames. A degenerate tree shaped like a linked list needs one frame per element.
Repeated work
When a function calls itself more than once, the same sub-problems can be computed many times. The naive Fibonacci function is the standard example.
fn fib(n: u32) -> u64 {
if n < 2 {
n as u64
} else {
fib(n - 1) + fib(n - 2)
}
}
fn main() {
println!("{}", fib(10));
}This prints 55. The number of calls grows exponentially with n, so fib(50) takes minutes. Two common fixes are memoization (storing results already computed) and iteration.
fn fib_iter(n: u32) -> u64 {
let (mut a, mut b) = (0u64, 1u64);
for _ in 0..n {
(a, b) = (b, a + b);
}
a
}
fn main() {
println!("{}", fib_iter(50));
}The loop version runs in linear time and constant stack space. It prints 12586269025.
Choosing recursion or a loop
| Situation | Better choice |
|---|---|
| Data is a tree or a nested structure | Recursion |
| Depth is small and bounded | Recursion, if it reads more clearly |
| Depth depends on untrusted input | Loop with an explicit `Vec` as a stack |
| Sub-problems overlap, as in Fibonacci | Loop or memoization |
| Simple counting or accumulating | Loop or iterator |
Common mistakes
- Missing or unreachable base case. The function never stops, and the program overflows the stack.
- Input that does not shrink. Calling
f(n)from insidef(n)is an infinite loop. Check that every recursive call moves toward the base case. - Unsigned subtraction.
n - 1on au64that is0overflows. Guard it with the base case, or usechecked_sub. - Forgetting the return type. A recursive function needs an explicit return type. Rust does not infer function signatures, even for recursive ones.
- Assuming tail calls are free. Rust may or may not optimize them, so test with the depth you expect.
Exercise
Write a recursive function fn sum_to(n: u32) -> u32 that returns 1 + 2 + ... + n, with sum_to(0) returning 0. Then explain why sum_to(1_000_000) is a risk in a debug build even though the answer fits in a u32's range only if you use a wider type. What would you change?
Show answer
A solution is fn sum_to(n: u32) -> u32 { if n == 0 { 0 } else { n + sum_to(n - 1) } }. There are two separate problems. First, sum_to(1_000_000) makes a million nested calls, which can exhaust the stack in a debug build. Second, the true result is 500,000,500,000, which does not fit in a u32 (maximum about 4.29 billion), so the addition overflows and panics in debug builds. Fix both by using a u64 return type and replacing the recursion with a loop ((1..=n as u64).sum()), or by using the closed form n * (n + 1) / 2 computed in u64.
Exercise
In the Tree example, add a function fn depth(tree: &Tree) -> usize that returns the number of nodes on the longest path from the root to a leaf. What are its base case and recursive case?
Show answer
The base case is Tree::Leaf(_), which returns 1. The recursive case is Tree::Node(left, right), which returns 1 + depth(left).max(depth(right)). The full function is fn depth(tree: &Tree) -> usize { match tree { Tree::Leaf(_) => 1, Tree::Node(l, r) => 1 + depth(l).max(depth(r)) } }. Each call receives a subtree, which is strictly smaller, so the recursion ends.