Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Rust Recursion


Share

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.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.