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
相关推荐
哈喽姥爷2 分钟前
Spring Boot---自动配置原理和自定义Starter
java·spring boot·后端·自定义starter·自动配置原理
啊?啊?27 分钟前
18 从对象内存到函数调用:C++ 虚函数表原理(继承覆盖 / 动态绑定)+ 多态实战
开发语言·c++·多态原理
bkspiderx33 分钟前
C++标准库:文件流类
开发语言·c++
siy23331 小时前
[c语言日记] 数组的一种死法和两种用法
c语言·开发语言·笔记·学习·链表
njxiejing1 小时前
Python NumPy安装、导入与入门
开发语言·python·numpy
Rhys..1 小时前
Python&Flask 使用 DBUtils 创建通用连接池
开发语言·python·mysql
舒一笑2 小时前
为什么where=Version就是乐观锁了?
后端·mysql·程序员
土了个豆子的2 小时前
04.事件中心模块
开发语言·前端·visualstudio·单例模式·c#
GoGeekBaird2 小时前
关于垂类AI应用落地行业的方法论思考
后端·github·agent
小宁爱Python2 小时前
Django 基础入门:命令、结构与核心配置全解析
后端·python·django