Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a Rust numeric type but only if it fits? [duplicate]

Tags:

rust

I want the following

(2u128.pow(x)) as u64

but such that it succeeds for x < 64 and fails for x >= 64.

like image 754
Sarien Avatar asked Oct 20 '25 15:10

Sarien


1 Answers

As you correctly pointed out yourself, you should use TryFrom, but you should also make sure the exponentiation itself doesn't overflow, by using u128::checked_pow instead of u128::pow:

use std::convert::TryFrom;

let x = 129;
let y = 2u128.checked_pow(x).expect("Number too big for exponentiation");
let z = u64::try_from(y).expect("Number too big for cast");

(playground link)

like image 197
Frxstrem Avatar answered Oct 23 '25 06:10

Frxstrem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!