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
相关推荐
Neobee2 分钟前
国内用 Terraform 管 Cloudflare 踩过的 5 个坑(附可直接复用的代码)
后端
平凡但不平庸的码农8 分钟前
Go context 包详解
开发语言·后端·golang
隐士Xbox8 分钟前
c++ 指针的用法
开发语言·c++·计算机视觉
江南十四行13 分钟前
Python元类编程——从type到metaclass的深度探索
开发语言·python
众乐乐_200817 分钟前
PHP 的进程 fork 机制
开发语言·php
yujunl19 分钟前
U9 WCF调试的一个坑
开发语言
lly20240622 分钟前
Scala 模式匹配
开发语言
2zcode23 分钟前
基于MATLAB卷积神经网络的多颜色车牌识别系统设计与实现
开发语言·matlab·cnn
无限进步_25 分钟前
【C++】从红黑树到 map 和 set:封装设计与迭代器实现
开发语言·数据结构·数据库·c++·windows·github·visual studio
Hello eveybody27 分钟前
介绍一下动态树LCT(Python)
开发语言·python·算法