How to Handle Recursion Safely in Rust (Stack Overflow Prevention)

Prevent Rust stack overflows by manually limiting recursion depth with a counter check or refactoring to an iterative loop.

Rust does not have a built-in mechanism to prevent stack overflows from recursion; you must manually limit depth or refactor to an iterative approach. Use a counter parameter to track depth and return an error or stop if it exceeds a safe threshold.

fn factorial(n: u32, depth: u32) -> Result<u64, &'static str> {
    if depth > 1000 {
        return Err("Recursion depth exceeded");
    }
    if n <= 1 {
        return Ok(1);
    }
    let sub = factorial(n - 1, depth + 1)?;
    Ok(n as u64 * sub)
}

fn main() {
    match factorial(5, 0) {
        Ok(v) => println!("Result: {}", v),
        Err(e) => println!("Error: {}", e),
    }
}