Recursion
A recursive function calls itself with a smaller input until a base case. In Rust each call is a stack frame; a deep recursion will overflow the stack even if the heap is empty.
Detailed Explanation
Recursion is a function that solves a problem by solving a smaller instance of the same problem. The base case returns without calling itself. The recursive case calls, then combines. Tree walks, DFS, divide-and-conquer, and many dynamic-programming-from-the-top formulations are recursive in the mind even when you later rewrite them as loops.
Rust does not tail-call-optimise reliably. A "tail recursive" function that a Scheme compiler would turn into a loop is still a stack frame per call in Rust. fn countdown(n: u32) { if n == 0 { return; } countdown(n - 1); } will overflow on a large n. Write a while loop. The compiler may inline a tiny recursion; it will not save you from a million frames.
The borrow checker changes how recursive structures look. A recursive type needs a Box, Vec, or other indirection: enum Tree { Leaf, Node(Box<Tree>, Box<Tree>) }. A recursive walk that holds a mutable borrow of a node cannot also recurse into that node through another path without splitting borrows (split_at_mut, indices, or taking the children out with mem::take).
Stack size is platform- and thread-dependent. The main thread often has a larger stack than a std::thread (which defaults to a couple of megabytes). A recursive DFS on a skewed 100_000-node tree belongs on an explicit Vec stack, not on the call stack.
When recursion is the right code: the data is a tree of modest depth, the algorithm is naturally divide-and-conquer, and n is bounded (AST walks, filesystem trees you trust). When you rewrite: graphs that may contain long paths, user-controlled depth, parsers of untrusted input.
When you reach for recursion: trees and clear base cases. When you reach for an explicit stack: graphs, unknown depth, or anything that already overflowed once.
Code Examples
fn fact(n: u64) -> u64 {
if n <= 1 {
1
} else {
n * fact(n - 1)
}
}
fn fact_loop(mut n: u64) -> u64 {
let mut out = 1;
while n > 1 {
out *= n;
n -= 1;
}
out
}
fn main() {
println!("{}", fact(5)); // prints: 120
println!("{}", fact_loop(5)); // prints: 120
}Common Gotchas
No guaranteed tail-call elimination
A tail-recursive function can still overflow. Use a loop when depth is unbounded.
Worker threads have smaller stacks than you think
Move deep recursion off `thread::spawn` or raise the stack size, or do not recurse.
Recursive types need indirection
`struct Node { child: Node }` does not compile. Use `Box` or a `Vec` of indices.
Mutable recursion needs split borrows
You cannot mutably recurse into a child while holding `&mut self` to the parent without restructuring.