From d252127e5bd40420ab3fe00cb4dfce42afc7bf03 Mon Sep 17 00:00:00 2001 From: JEB-him <76830802+JEB-him@users.noreply.github.com> Date: Thu, 25 Sep 2025 22:01:05 +0800 Subject: [PATCH] Fix integer overflow explanation in data_types.md Corrected the description of integer overflow behavior in Rust, clarifying the wrapping behavior in release mode. --- src/programming_concepts/data_types.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/programming_concepts/data_types.md b/src/programming_concepts/data_types.md index 7fa8017..7e66d8e 100644 --- a/src/programming_concepts/data_types.md +++ b/src/programming_concepts/data_types.md @@ -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 行为,被视为错误。 > > 要显式地处理溢出的可能性,咱们可以使用标准库为原始数值类型,提供的下面这些方法系列: >