I wrote this code:
fn main() {
let mut k: i64 = 1;
loop {
k = k * 10;
println!("cool {}", k);
}
}
If I run cargo run I get:
cool 10
cool 100
cool 1000
cool 10000
cool 100000
cool 1000000
cool 10000000
cool 100000000
cool 1000000000
cool 10000000000
cool 100000000000
cool 1000000000000
cool 10000000000000
cool 100000000000000
cool 1000000000000000
cool 10000000000000000
cool 100000000000000000
cool 1000000000000000000
thread 'main' panicked at 'attempt to multiply with overflow', src/main.rs:4:14
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
But if I run the executable after cargo build --release (in release dir), I get an infinite loop:
cool 0
cool 0
cool 0
cool 0
cool 0
cool 0
...
I know that "In a release build, the operation wraps around: it produces the value equivalent to the mathematically correct result modulo the range of the value" but I do not understand well why I do not get '0' in debug mode.
I have also tried:
fn main() {
let mut k: i32 = 1;
loop {
k = k * 10;
println!("cool {}", k);
k.checked_mul(10).expect("overflow!");
}
}
and got:
cool 10
cool 100
cool 1000
cool 10000
cool 100000
cool 1000000
cool 10000000
cool 100000000
cool 1000000000
thread 'main' panicked at 'overflow!', src/main.rs:6:27
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Why?