Consider the following code:
let mut val : u8 = 125; let deltas : [i8; 4] = [5, -5, 5, 5]; let delta = select_current_delta(deltas); val += delta;
It seems simple. I want to either increase or decrease the byte value based on some criteria (and I have a way to prevent overflow of the u8 value).
This, of course, does not compile:
> rustc lala.rs lala.rs:7:12: 7:17 error: mismatched types: expected `u8`, found `i8` (expected u8, found i8) [E0308] lala.rs:7 val += delta; ^~~~~
Duh! Mixing signed and unsigned types seems to be prohibited in Rust. How about this?
val = (val as i8 + delta) as u8;
This compiles, but when I try to run it ...
> ./lala thread '<main>' panicked at 'arithmetic operation overflowed', lala.rs:7
Yes, i8 maximum value of 125, adding 5 will overflow, although the value is great for u8 .
I was able to come up with two solutions that work:
val = (val as i16 + delta as i16) as u8; // or if delta < 0 { val -= (-delta) as u8 } else { val += delta as u8}
None of them seem elegant to me. Is there an idiomatic way to add u8 to i8?