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
相关推荐
apcipot_rain1 小时前
C++开发 面试 1Day速通
开发语言·c++·面试
时间的情敌1 小时前
Three.js GLTF 阀门 / 泵体模型加载、材质修改、状态联动(正常 / 故障 / 告警变色)
开发语言·javascript·three.js·材质
大数据技术派2 小时前
有了AI,你多久没有亲自写代码了?
后端
星恒随风2 小时前
从0实现C++ AI大模型接入SDK(七):Ollama本地模型部署、NDJSON流式响应与LLMManager模型管理
linux·开发语言·c++·人工智能·笔记
考虑考虑2 小时前
JDK27的LazyConstant
java·后端·java ee
知识搬运临时工3 小时前
加一层连接池,TPS 从 26438 掉到 12923
java·后端
琳少_3 小时前
java课堂笔记
java·开发语言·数据库·笔记
周末程序猿3 小时前
技术总结|OpenSpec 实战:如何先写规格,再让 AI 写代码
后端·ai编程
Brain 博览记4 小时前
脑机接口研究丨FPGA 5 毫秒完成运动想象分类
开发语言·论文阅读·人工智能·机器学习·fpga开发·分类·数据挖掘
计算机–阿拉升学长4 小时前
基于SpringBoot的番茄种植水肥一体化管理系统 — 系统设计与实现
java·spring boot·后端·mysql·vue·javaweb