Help to give out the correct number or error

Hey. I have a program that raises a number to a power. But if, for example, in my function the type of all the numbers i8 and my result is more or less than the number 127 and -128, I get to get panic (this is in IDE), but in the usual console I get some random numbers, even negative ones that number with a plus sign.
This test helps, but very crookedly:

if result > 127 || result < -128 || number >= 0 && result < 0 {
    println!("Some error text..");
} else {
    println!("Result: {}", result);

How to solve this problem?

P.S. This is my simple pow function:

fn pow(n: i8, p: i8) -> i8 {
    if p == 1 {
        return n;

    n * pow(n, p - 1)

Is it possible for me to handle this function using a match? I tried, but it did not work :frowning:

add to Cargo.toml


or use checked or overflowing functions.

1 Like

Note that the first two conditions can never be true, since you’re testing whether the i8 is out of its limits, which it can never be.


In principle it is your responsibility to never allow operation to produce a value that is too large for its type. In release mode Rust allows values to silently overflow.

There’s checked_mul and checked_pow that can tell you when the result is out of range.