rust attempt to multiply with overflow code example

Example: rust attempt to multiply with overflow

/*
For the value to be u8, all operands of the expression need to be u8 as well.
The expression 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 doesn’t fit into a u8
which is why the compiler complains.

It works if you write it like this:
*/

fn main() {
    let x: u8 = (2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 - 1) as u8;
    println!("{}", x);
}

/*
This way the 2s and the 1 will be 64 or 32 bit integers and
the final result is then converted into u8.

You can also just use a bigger type like i32 or i64.
*/

Tags:

Misc Example