Exponent protecting against overflow - checked_pow, saturating_pow
-
checked_pow
-
saturating_pow
-
As many other mathematical operations, calling
pow
can also create a number that does not fit in the expected type and then the code wouldpanic!
. -
We can use the checked_pow that returns an Option
-
It contains the computed value, if successful or
None
if there was an overflow. -
An alternative way is to use saturating_pow.
fn main() { let x: i8 = 10; let y: i8 = 16; let z = x.pow(2); println!("{}", z); // 100 // let z = y.pow(2); // panic: attempt to multiply with overflow let z = x.checked_pow(2).unwrap(); println!("{}", z); // 100 // let z = y.checked_pow(2).unwrap(); // panic: called `Option::unwrap()` on a `None` value let z = y.checked_pow(2).unwrap_or(0); println!("{}", z); // 0 let z = match y.checked_pow(2) { Some(val) => val, None => { eprintln!("overflow"); std::process::exit(1); } }; println!("{}", z); // isn't reached if there is an overflow }