Fix integer overflow explanation in data_types.md

Corrected the description of integer overflow behavior in Rust, clarifying the wrapping behavior in release mode.
This commit is contained in:
JEB-him
2025-09-25 22:01:05 +08:00
committed by GitHub
parent 123c0715dd
commit d252127e5b

View File

@@ -94,7 +94,7 @@ error: could not compile `data_types` (bin "data_types") due to previous error
>
> 假设咱们有个可保存 0 到 255 之间值的 `u8` 类型变量。在咱们尝试将该变量,更改为超出该范围的某个值,比如 256 时,就会发生 *整数溢出integer overflow*这可能导致两种行为之一。在咱们以调试模式编译时Rust 包含了对那些发生时,会引起咱们程序 *中止panic* 的整数溢出的检查。当某个程序以一个报错而退出时Rust 便对此使用 *中止panicking* 一词;我们将在第 9 章,[“使用 `panic!` 的无法恢复错误](../error_handling/panic.md) 小节中,更深入地讨论中止运行。
>
> 而使用 `--release` 命令行开关在发布模式下编译时Rust 就不会检查会导致中止运行的整数溢出。相反如果发生溢出Rust 会执行 *二的补码换行two's complement wrapping*。简而言之,大于该类型所能容纳最大值的值,会 “折回wrap around” 到该类型所能容纳的最小值。在 `u8` 的情况下,值 256 会变成 0值 257 会变成 1依此类推。程序不会中止运行但变量的值可能不是咱们期望的值。依赖整数溢出的 wrapping 行为,被视为错误。
> 而使用 `--release` 命令行开关在发布模式下编译时Rust 就不会检查会导致中止运行的整数溢出。相反如果发生溢出Rust 会执行 *补码回绕two's complement wrapping*。简而言之,大于该类型所能容纳最大值的值,会 “折回wrap around” 到该类型所能容纳的最小值。在 `u8` 的情况下,值 256 会变成 0值 257 会变成 1依此类推。程序不会中止运行但变量的值可能不是咱们期望的值。依赖整数溢出的 wrapping 行为,被视为错误。
>
> 要显式地处理溢出的可能性,咱们可以使用标准库为原始数值类型,提供的下面这些方法系列:
>