Reputation: 4884
Why isn't the following Rust-Code failing?!
fn main() {
let a:usize = -2;
assert!(a == -2);
}
a
can't be negative. Neither of both is happening, why?
Shouldn't the compiler protect me from common overflow issues?
Upvotes: 6
Views: 4783
Reputation: 299880
Up until now, Rust has defined the semantics of underflow and overflow on integral types as wrap-around modulo 2. Therefore, assigning -2
to an unsigned integer is simply asking for its maximum minus one.
Those semantics are being challenged right now and the gist of it is that for 1.0 underflow and overflow will yield an unspecified value (and possibly panic!
); though for performance reasons the tests will only be systemic in Debug mode and will be disabled by default in Release mode.
In this new direction, it would be reasonable to consider assigning a negative value to an unsigned integer an error, and I can only invite you to chime in on the linked RFC so as to voice your concern.
Upvotes: 9