Rust安全之数值

文章目录

数值溢出

编译通过,运行失败

cargo run 1

rust 复制代码
fn main() {
    let mut arg = std::env::args()
        .skip(1)
        .map(|x| x.parse::<i32>().unwrap())
        .next()
        .unwrap();
    let m_i = i32::MAX - 1;
    let a = m_i + arg;

    println!("{:?}", a);
}
bash 复制代码
thread 'main' panicked at 'attempt to add with overflow', src\bin\rssh3.rs:13:13
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
error: process didn't exit successfully: `target\debug\rssh3.exe 1` (exit code: 101)

编译不通过

rust 复制代码
fn main() {
    let m_i = i32::MAX;
    let a = m_i + 1;

    println!("{:?}", a);
}

输出

bash 复制代码
error: this arithmetic operation will overflow
 --> src\bin\rssh3.rs:9:13
  |
9 |     let a = m_i + 1;
  |             ^^^^^^^ attempt to compute `i32::MAX + 1_i32`, which would overflow
  |
  = note: `#[deny(arithmetic_overflow)]` on by default

warning: `datetime-util` (bin "rssh3") generated 4 warnings
error: could not compile `datetime-util` due to previous error; 4 warnings emitted
相关推荐
AI小云5 分钟前
【Numpy数据运算】数组间运算
开发语言·python·numpy
weixin_4365250717 分钟前
SpringBoot 单体服务集成 Zipkin 实现链路追踪
java·spring boot·后端
q***783721 分钟前
【玩转全栈】----Django制作部门管理页面
后端·python·django
是苏浙33 分钟前
零基础入门C语言之C语言实现数据结构之单链表经典算法
c语言·开发语言·数据结构·算法
纵有疾風起40 分钟前
C++—vector:vecor使用及模拟实现
开发语言·c++·经验分享·开源·stl·vector
Yeats_Liao1 小时前
时序数据库系列(八):InfluxDB配合Grafana可视化
数据库·后端·grafana·时序数据库
任子菲阳1 小时前
学Java第四十三天——Map双列集合
java·开发语言
wearegogog1231 小时前
基于MATLAB的谷物颗粒计数方法
开发语言·matlab
Jackson@ML1 小时前
360度看C#编程语言
开发语言·c#
我命由我123451 小时前
CesiumJS 案例 P35:添加图片图层(添加图片数据)
开发语言·前端·javascript·css·html·html5·js