小编Jun*_*hee的帖子

在Rust中,为什么整数溢出有时会导致编译错误或运行时错误?

fn main() {
    let num: u8 = 255;
    let num2: u8 = num + 1;
    println!("{}, {}", num, num2);
}

Run Code Online (Sandbox Code Playgroud)

当 时$ cargo build --release,这段代码不会产生编译错误。并且$ cargo run,产生运行时错误。

线程“main”因“尝试添加溢出”而惊慌失措,src/main.rs:3:20 注意:使用RUST_BACKTRACE=1环境变量运行以显示回溯

这没关系。但我不明白的是下面的情况。当我删除 println 行时,会出现编译错误。

fn main() {
    let num: u8 = 255;
    let num2: u8 = num + 1;
}
Run Code Online (Sandbox Code Playgroud)
$ cargo build --release

error: this arithmetic operation will overflow
 --> src/main.rs:3:20
  |
3 |     let num2: u8 = num + 1;
  |                    ^^^^^^^ attempt to …
Run Code Online (Sandbox Code Playgroud)

integer-overflow rust

20
推荐指数
1
解决办法
1449
查看次数

标签 统计

integer-overflow ×1

rust ×1