如何在 Rust 中返回整数溢出的标志? [英] How do I return a flag on integer overflow in Rust?

查看:198
本文介绍了如何在 Rust 中返回整数溢出的标志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swift 有整数溢出算术函数,无论数字是否溢出,它都会返回一个标志.我们在 Rust 中有相同的东西吗?

Swift has integer overflow arithmetic functions which return a flag whether the number has overflowed or not. Do we have same thing in Rust?

推荐答案

如您所见,有 intrinsics 用于此,但这些是 unsafe 并且使用起来有些烦人.

As you note, there are intrinsics for this but these are unsafe and somewhat annoying to use.

在 Rust 1.0 之前,标准库以 CheckedAdd, CheckedSub, CheckedMulCheckedDiv.

Before Rust 1.0, the standard library provided wrappers that detect the overflow for the 4 arithmetic operations in the form of CheckedAdd, CheckedSub, CheckedMul and CheckedDiv.

从 Rust 1.0 开始,这些特征不再存在,每个数字类型只有固有的方法,例如 i32::checked_add.

As of Rust 1.0, these traits no longer exist and there are just inherent methods on each numeric type, such as i32::checked_add.

然而,这些只是检测溢出而不返回溢出结果:

However, these just detect overflow and do not return the overflowed-result:

fn main() {
    println!("{:?}", 5u16.checked_add(65530u16));
    println!("{:?}", 6u16.checked_add(65530u16));
}

(playground)

打印:

Some(65535)
None

这篇关于如何在 Rust 中返回整数溢出的标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆