当整数算术运算溢出时,Rust 编程语言会发生什么?

What happens in Rust programming language when an integer arithmetic operation overflows?

据我所知,在 C 编程语言(以及许多基于 C 的语言)中,当算术运算溢出 N 位整数时,该溢出会将结果缩短为模 2 的 N 次方, 仅保留结果的 LSB。

在 Rust 编程语言中,当这样的整数算术运算溢出时会发生什么。

当您在调试模式下编译时,Rust 会检查整数溢出,如果发生这种行为,会导致您的程序在运行时崩溃。

当您使用 --release 标志在发布模式下编译时,Rust 不包括对导致恐慌的整数溢出的检查。对于带符号的值,结果基于二进制补码包装。对于无符号值,结果是对类型的最大值 + 1 取模。

标准库有许多函数可以更好地控制在溢出情况下应该发生什么,例如 checked_add, wrapping_add 和其他一些变体。

如果您还没有阅读,我建议阅读 The Rust Programming Language, which has a section 专门解决这个问题。

来自Rust Reference, chapter "Behavior not considered unsafe"

Integer oveflow

If a program contains arithmetic overflow, the programmer has made an error. In the following discussion, we maintain a distinction between arithmetic overflow and wrapping arithmetic. The first is erroneous, while the second is intentional.

When the programmer has enabled debug_assert! assertions (for example, by enabling a non-optimized build), implementations must insert dynamic checks that panic on overflow. Other kinds of builds may result in panics or silently wrapped values on overflow, at the implementation's discretion.

In the case of implicitly-wrapped overflow, implementations must provide well-defined (even if still considered erroneous) results by using two's complement overflow conventions.

The integral types provide inherent methods to allow programmers explicitly to perform wrapping arithmetic. For example, i32::wrapping_add provides two's complement, wrapping addition.

The standard library also provides a Wrapping<T> newtype which ensures all standard arithmetic operations for T have wrapping semantics.

See RFC 560 for error conditions, rationale, and more details about integer overflow.

因此,根据您的编译器设置,您的程序可能会在溢出时崩溃或自动换行。依赖于其中任何一种行为都不是一个好主意。如果您需要处理溢出的可能性,请使用包装函数明确地告诉编译器您想要并期望溢出回绕,或者使用 u32::checked_add 等检查方法手动处理溢出。