fn main() {
let num: u8 = 255;
let num2: u8 = num + 1;
println!("{}, {}", num, num2);
}
值为$ cargo build --release
时,此代码不会出现编译错误.
$ cargo run
、制造运行时错误.
线程‘main’在‘try 添加时溢出’时死机,src/main.rs:3:20 注意:使用
RUST_BACKTRACE=1
环境变量运行可显示回溯
这样就可以了.但我不明白的是下面的情况. 当我删除println行时,会出现编译错误.
fn main() {
let num: u8 = 255;
let num2: u8 = num + 1;
}
$ cargo build --release
error: this arithmetic operation will overflow
--> src/main.rs:3:20
|
3 | let num2: u8 = num + 1;
| ^^^^^^^ attempt to compute `u8::MAX + 1_u8`, which would overflow
|
= note: `#[deny(arithmetic_overflow)]` on by default
为什么整数溢出有时会导致编译错误或运行时错误?