Tsallaka zuwa abun ciki
Justice Tech School

Recursion

A function can call itself. Always have a base case. Rust does not guarantee tail call optimisation, so deep recursion can overflow the stack.

Example
fn fact(n: u64) -> u64 { if n <= 1 { 1 } else { n * fact(n - 1) } }
fn fib(n: u32) -> u32 { if n < 2 { n } else { fib(n - 1) + fib(n - 2) } }
fn main() {
    println!("{} {}", fact(10), fib(10));
}

Result

3628800 55

Exercise

Return 1 in the base case.

if n <= 1 {  } else { n }

Quiz Test

What stops recursion?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.