factorial create panic


In order to avoid this stack overflow our function needs to check the input and then if it is a negative number then report it. (I know, instead of i64 we could have used u64 which is an unsigned integer that would only allow non-negative numbers. but in other functions we might not be able to use the type-system for that. e.g. what if we expect a positive whole number larger than 2?

One way to avoid reaching stack overflow is to call panic! ourselves.


examples/errors/factorial-create-panic/src/main.rs
fn main() {
    for number in [5, 10, 0, -1, 3] {
        let fact = factorial(number);
        println!("{number}! is {fact}");
    }
}

fn factorial(n: i64) -> i64 {
    if n < 0 {
        panic!("Cannot compute factorial of negative number");
    }
    if n == 0 {
        return 1;
    }
    n * factorial(n - 1)
}

Please type in a number: 10
10! is 3628800
Please type in a number: 0
0! is 1
Please type in a number: -1
thread 'main' panicked at 'Cannot compute factorial of negative number', examples/errors/factorial_create_panic.rs:14:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace