Learning Rust: Part 2

Been busy at it with the 100 exercises to learn Rust in the small free time that I could find. In the previous post I wrote a recursive factorial function, now it is time to do it in a while loop and a for loop.

Examples

Here's the while loop that I came up with:

pub fn factorial(n: u32) -> u32 {
    let mut num: u32 = n;
    if n <= 1 {
        return 1;
    }
    let mut sum = num;
    while num > 1 {
        sum *= (num - 1);
        num = num - 1;
    }
    return sum;
}

Do feel free to judge the craftsmanship! Here's the for loop, which turned out to be the simplest:

pub fn factorial(n: u32) -> u32 {
    let mut sum: u32 = 1;
    for i in 1..=n {
        sum *= i;
    }
    return sum;
}

I can appreciate the amount of tools and being able to choose the right one for the right job. I think Rust is a nice language (for now, at least). I'm pretty sure I'll have the fights that everyone keeps talking about, with the borrow checker and all that jazz but for simple stuff I think this will do just well!

In my opinion Rust will indeed be the future of lower level development. I do not think C++ will be deprecated what with the amount of code we have in it, but the next decade I believe Rust will overtake it. A new generation of developers are arriving and they like Rust.

Discussion

Comments

New comments are moderated before they appear publicly.

0 approved comments

No comments yet.