Avatar ·

How to implement recursion in Rust?

Hello everyone! I'm trying to implement a recursive function to calculate factorial in Rust, but I've encountered an unexpected problem. I wrote simple code:

fn factorial(n: u32) -> u32 {\n    if n == 0 {\n        1\n    } else {\n        n * factorial(n - 1)\n    }\n}\n\nfn main() {\n    println!("{}", factorial(5));\n}

The code compiles and works, but when I try to increase the recursion depth (e.g., factorial(20000)), the program crashes with a stack overflow. I know that Rust doesn't have tail call optimization, and this is expected. However, I want to understand how to properly implement recursion in Rust when the depth can be large.

What I've already tried:

  • Using an iterative approach with a loop (works, but I specifically want recursion)
  • Tried to write a tail