知识卡片
整数运算要选定边界行为
整数除法向零取整,-5 / 2 得 -2,-5 % 2 得 -1。直接除零始终触发 panic;需要自行处理失败时可用 checked_div,根据 Option 的结果决定处理方式。需要明确的溢出环绕时可调用 wrapping_add,表达所选的边界语义。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Expressions 判断边界算术、位运算和布尔短路 · 查看原书依据
Integer division rounds toward zero, and dividing an integer by zero triggers a panic even in release builds.
参考来源
- 位置:《Programming Rust Fast, Safe Systems Development, 3rd ed. (First Early Release)》第05章《Expressions》|判断边界算术、位运算和布尔短路,来源项目 `book-source`,`extracted/Programming Rust Fast, Safe Systems Development, 3rd ed. (First Early Release)/_epub-src/OEBPS/ch05.xhtml#arithmetic-bitwise-comparison-and-logical-operators`
- 结论依据:原文说明调试构建的溢出检查、始终拒绝直接除零、checked_div 的返回形式和向零取整对余数符号的影响。
- 原始内容:Integer division rounds toward zero, and dividing an integer by zero triggers a panic even in release builds.