DEV Community

Cover image for Day 19: Unleashing Recursion Magic in Rust: Finding Factorial! πŸš€
Aniket Botre
Aniket Botre

Posted on

Day 19: Unleashing Recursion Magic in Rust: Finding Factorial! πŸš€

Today on Day 19 of #100DaysOfCode, I embarked on the adventurous journey of solving the classic factorial problem using recursion in Rust. While I've tackled this challenge in other languages, I was eager to witness Rust's unique twist on this recursive saga.


The Rusty Recursion Spell ✨

I crafted a nifty function that takes a number as input and gracefully returns its factorial. Rust's syntax dances elegantly with recursion, making the code concise and expressive.

fn factorial(&num: &u128) -> u128 {
    if num == 1 {
        return 1;
    }

    num * factorial(&(num - 1))
}
Enter fullscreen mode Exit fullscreen mode

The Rust code begins by defining a factorial function that takes a reference to a u128 integer and recursively calculates its factorial. The base case checks if the input is 1, returning 1.


User Interaction with Rust Charm βœ¨πŸ€–

To sprinkle some user interaction magic, I decided to accept input from the command line. A loop diligently requests the user for input until a valid number graces the input stream. Parsing the input, I summoned the factorial function and presented the result in a grand finale.

fn main() {
    let mut user_input = String::new();
    let num: u128;

    println!("Enter a number: ");
    loop {
        io::stdin()
            .read_line(&mut user_input)
            .expect("Failed to read input, please try again");

        num = match user_input.trim().parse() {
            Ok(num) => num,
            _ => {
                println!("Please enter a valid number!!");
                continue;
            }
        };
        break;
    }

    let result = factorial(&num);
    println!("Factorial of {} is {}", num, result);
}
Enter fullscreen mode Exit fullscreen mode

In the main function, user input is acquired in a loop, ensuring validity, and then passed to the factorial function. The result is printed, showcasing Rust's robust error handling and efficient memory management. The code exemplifies Rust's conciseness, clarity, and adherence to ownership principles, fostering a deeper understanding of recursion and user input handling in the language.


Enchanting Learnings Along the Way πŸ“š

  • Recursion Reigns Supreme: Recursive solutions unveil the true power of programming, and Rust elegantly embraces this paradigm.

  • Rust's Mastery Unveiling: Learning Rust goes beyond syntax; it's about adapting to Rust's mindset. Designing functions with a focus on references highlights the language's memory efficiency prowess.

The Rusty spellbook continues to unfold its pages, and I'm savoring every enchanting chapter. Stay tuned for more Rusty adventures! πŸ¦€βœ¨

RustLang #RecursionMagic #CodeNewbie #LearningRust #ProgrammingJourney

Top comments (0)