Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

factorial function, runtime panic

  • panic!

  • In this series of examples we’ll see how a function we write can report error and how the caller can handle the error.

  • In the first example we implement a function to calculate factorial recursively. The specific task is not important, just that if the user supplies a negative number then this code will crash. More precisely, it will have a panic when our program reaches stack overflow.

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 {
        return 1;
    }
    n * factorial(n - 1)
}
Please type in a number: 5
5! is 120
Please type in a number: 10
10! is 3628800
Please type in a number: -1

thread 'main' has overflowed its stack
fatal runtime error: stack overflow
./rust.sh: line 19: 13666 Aborted                 (core dumped) ./myexe $*