|
|
|
|
|
by estebank
620 days ago
|
|
> By default Rust's release builds give the integer overflows wrapping, so (1u8 + 255u8 == 0u8) rather than panic, so as to avoid paying for the checks. I consider that to have been a mistake, and hopefully one we can change. Note that this is about defaults, you can build your own project as release with overflow panics. I'd wish the language had a mechanism to select the math overflow behavior in a more granular way that can be propagated to called functions (in effect, I want integer effects) instead of relying exclusively in the type system: fn bar(a: i32, b: i32) -> i32 where i32 is Saturating {
a + b
}
fn foo(a: i32, b: i32) -> i32 where i32 is Wrapping {
// the `a + b` wraps on overflow, but the call to
// bar overrides the effect of the current function
// and will saturate instead.
a + b + bar(a, b)
}
With this crates can provide control to their callers on math overflow behavior without having to provide type parameters in every API with a bounds for something like https://docs.rs/num-traits/0.2.19/num_traits/. |
|
Personally I'm not as bothered about this as I was initially, whereas I'm at least as annoyed today by some 'as' casts as I was when I learned Rust -- if I could have your integer effects or abolish narrowing 'as' then I'd abolish narrowing 'as' in a heartbeat. Let people explicitly say what they meant, if I have a u16 and I try to put that in a u8, it will not fit, make me write the fallible conversion and say what happens when it fails. This strikes me as especially hazardous for inferred casts. foo as _ could do more or less anything, it is easily possible that it does something I hadn't considered and will regret, make me write what I meant and we'll avoid that.