Rust Recursion
Recursion
Recursion means that a function calls itself.
Why would a function call itself? Some problems contain a smaller copy of the same problem. To count down from 5, you say "5", and then you count down from 4. To count down from 4, you say "4", and then you count down from 3, and so on.
A recursive function does one small step, and then calls itself to do the rest:
Example
fn countdown(number: i32) {
if number > 0 {
println!("{}", number);
countdown(number - 1);
} else {
println!("Liftoff!");
}
}
fn main() {
countdown(5);
}
Try it Yourself »
Example explained
countdown(5) prints 5 and calls countdown(4).
countdown(4) prints 4 and calls countdown(3), and so on.
Finally, countdown(0) prints "Liftoff!" instead, because 0 > 0 is false. It does not call itself again, so the calls stop.
Halting Condition
Every recursive function needs a halting condition: a condition where the function stops calling itself.
In the example above, the function stops when number becomes 0. It works like the condition in a while loop.
Without a halting condition, the function calls itself forever:
Example
fn countdown(number: i32) {
println!("{}", number);
countdown(number - 1); // Never stops
}
Each function call uses a little memory. After many thousands of calls, there is no more memory left, and the program crashes with a "stack overflow" error.
Sum of Numbers
A recursive function can also return a value. This function adds all numbers from 1 to 10:
Example
fn sum(number: i32) -> i32 {
if number > 0 {
number + sum(number - 1)
} else {
0
}
}
fn main() {
let result = sum(10);
println!("{}", result);
}
Try it Yourself »
Example explained
sum(10) returns 10 + sum(9).
sum(9) returns 9 + sum(8), and so on.
sum(0) returns 0. This is the halting condition, so the calls stop.
Then all the numbers are added together: 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0, which is 55.
Remember from the Functions chapter: the last line of a function, without a semicolon, is the return value. Here, the if part and the else part each give one value.
Factorial
The factorial of a number is the number multiplied by every whole number below it, down to 1. For example, the factorial of 5 is 5 * 4 * 3 * 2 * 1, which is 120.
It is the same idea: the factorial of 5 is 5 times the factorial of 4:
Example
fn factorial(number: u64) -> u64 {
if number > 1 {
number * factorial(number - 1)
} else {
1
}
}
fn main() {
println!("{}", factorial(5));
}
Try it Yourself »
Here, the halting condition is when number is 1: factorial(1) returns 1, and the calls stop.
The example uses u64, a bigger unsigned integer type than u32, because factorials grow very fast.
Note: Recursion and loops can often solve the same problems. For simple counting, a loop is often easier to read. Recursion is useful for problems that split into smaller copies of themselves, like folders that contain other folders.