If I try to substract into the negative from an usize integer rust panics.
<code>fn main() {
let a: usize = 1;
println!("{}", a - 5);
}
</code>
<code>fn main() {
let a: usize = 1;
println!("{}", a - 5);
}
</code>
fn main() {
let a: usize = 1;
println!("{}", a - 5);
}
<code>error: this arithmetic operation will overflow
</code>
<code>error: this arithmetic operation will overflow
</code>
error: this arithmetic operation will overflow
But I can cast an i32
to usize
and get an overflow without any warnings or errors:
<code>fn main() {
let a: i32 = -1;
let b: usize = a as usize;
println!("{}", b);
}
</code>
<code>fn main() {
let a: i32 = -1;
let b: usize = a as usize;
println!("{}", b);
}
</code>
fn main() {
let a: i32 = -1;
let b: usize = a as usize;
println!("{}", b);
}
<code>18446744073709551615
</code>
<code>18446744073709551615
</code>
18446744073709551615
Is there a better way to casting this? I’ll just avoid casting i32
to usize
or check manually for overflows, but it is surprising to me that I can get this overflow so easily in Rust.