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
相关推荐
爱吃提升7 分钟前
Dev-C++ 5.11 C++断点调试完整教程
开发语言·c++
夜晚回家13 分钟前
Python 原始字符串详解 | r 前缀到底让什么不再转义
开发语言·python
suhan17 分钟前
【数据结构】三、栈和队列:6.链队列、双端队列、队列的应用(树的层次遍历、广度优先BFS、先来先服务FCFS)
数据结构·后端·算法
neoooo19 分钟前
🚀Claude Code 小技巧(二):找回会话,撤销修改
前端·人工智能·后端
陈年老古董19 分钟前
PyQt5 入门指南:环境搭建、PyCharm 外部工具配置与登录界面实战
开发语言·qt·pycharm
数据库小学妹22 分钟前
向量检索最小可运行实现:HNSW索引参数与召回率/延迟权衡
数据库·后端
姜鱼问生22 分钟前
Docker Volume 备份与恢复实战:不停机迁移数据
后端·算法·架构
suhan22 分钟前
【数据结构】三、栈和队列:5.顺序队列(循环队列)(初始化,判空判满,入队,出队,实例)
数据结构·后端·算法
看浪的路人23 分钟前
第7讲:大模型后端服务化——Go 实现高并发 LLM Proxy / Router / Fallback
开发语言·后端·golang
suhan23 分钟前
【数据结构】三、栈和队列:3.链栈(链栈栈的初始化,判空,进栈,出栈,读取栈顶,链栈实例)
数据结构·后端·算法