I'm currently trying to learn the basics of the Rust programming language, to do this my first piece of code after the classic 'Hello World' was a simple recursive Factorial function.
This is the code:
use std::io;
fn factorial(num: i64) -> i64 {
return if num == 1 {
1
}else{
num * factorial(num - 1)
}
}
fn trim_newline(s: &mut String){
if s.ends_with('\n'){
s.pop();
if s.ends_with('\r'){
s.pop();
}
}
}
fn main() {
let mut user_input = String::new();
println!("Welcome to rust-factorial!");
loop {
user_input.clear();
println!("Please enter a number:");
match io::stdin().read_line(&mut user_input) {
Ok(_) => (),
Err(_e) => {
println!("error: {}", _e);
continue;
},
};
let num: i64 = match user_input.trim().parse::<i64>() {
Ok(n) => n,
Err(_e) => {
trim_newline(&mut user_input); // remove trailing newline
println!("'{}' is not a valid number, full error: {}", user_input, _e);
continue;
},
};
println!("{}! is equal to {}", num, factorial(num));
}
}
I am aware of one major issue with my current approach which is that the biggest number this program can calculate is the 20th number of the sequence. Asking for a number bigger than 20 results in the following error on my machine:
Please enter a number:
24
thread 'main' panicked at 'attempt to multiply with overflow', src\main.rs:7:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
error: process didn't exit successfully: `target\debug\rust-factorial.exe` (exit code: 101)
I'd like to know a few things:
- How can I change this code to be more "rust-like"
- (by that I mean 'pythonic' but for rust)
- What would the rust approach be for solving the overflow that happens with numbers past 20?
- (I could either hard-code the limit or something to that effect but I'm curious whether or not there is a guideline about this from a Rust perspective)
- Any and all comments on code quality, readability and potentially efficiency
0!=1
. I think your implementation Will go crazy when you input zero. \$\endgroup\$