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
相关推荐
喵了meme6 小时前
C语言实战4
c语言·开发语言
码界奇点6 小时前
Python从0到100一站式学习路线图与实战指南
开发语言·python·学习·青少年编程·贴图
码事漫谈6 小时前
C++ 多线程开发:从零开始的完整指南
后端
9ilk6 小时前
【C++】--- 特殊类设计
开发语言·c++·后端
码事漫谈6 小时前
十字路口的抉择:B端与C端C++开发者的职业路径全解析
后端
sali-tec7 小时前
C# 基于halcon的视觉工作流-章68 深度学习-对象检测
开发语言·算法·计算机视觉·重构·c#
提笔了无痕7 小时前
git基本了解、常用基本命令与使用
git·后端
java1234_小锋8 小时前
Spring IoC的实现机制是什么?
java·后端·spring
喵个咪8 小时前
开箱即用的 GoWind Admin|风行,企业级前后端一体中后台框架:JWT 集成指南
后端·go
生骨大头菜8 小时前
使用python实现相似图片搜索功能,并接入springcloud
开发语言·python·spring cloud·微服务