Checked Arithmetic Instead Of Overflow Panics
checked_add and checked_mul return None on overflow, saturating helpers clamp at the type bounds, and wrapping_add documents modular wraparound.
Code
fn add_cents(a: i64, b: i64) -> Result<i64, String> {
// checked 算术溢出时返回 None:把 overflow 变成显式错误而不是 panic
a.checked_add(b).ok_or_else(|| format!("i64 overflow: {a} + {b}"))
}
fn main() {
let price_cents = 19_990_000_000i64;
let qty = 500_000i64;
println!("total: {:?}", add_cents(price_cents, qty));
let max = i64::MAX;
println!("checked_add at max: {:?}", max.checked_add(1)); // None
// saturating:封顶在类型边界,适合预算/限流的"到顶即停"语义
println!("saturating_add: {}", max.saturating_add(1));
// wrapping:显式声明回绕语义(debug 构建里普通 + 溢出会 panic)
println!("wrapping_add: {}", max.wrapping_add(1));
// 乘法同样会溢出
println!("checked_mul: {:?}", qty.checked_mul(1_000_000_000_000_000));
}How the snippet works
Checked Arithmetic Instead Of Overflow Panics is built around the functions add_cents and main.
Result turns the error into data — visible in the type, handled by the caller.
What to watch for
- The
Resultvalues will not let errors pass silently; each must be matched, unwrapped, or propagated.
Using it
The primary signature is fn add_cents(a: i64, b: i64) -> Result<i64, String>
The run emits 5 labeled sections — total:, checked_add at max:, saturating_add:, wrapping_add:, checked_mul: — one per step.
The entry point wires add_cents together — run it once and the whole demo flows.
Key statements
fn add_cents(a: i64, b: i64) -> Result<i64, String> {
// checked 算术溢出时返回 None:把 overflow 变成显式错误而不是 panic
a.checked_add(b).ok_or_else(|| format!("i64 overflow: {a} + {b}"))
}
Interactive Tools for This Topic
FAQ
- How should callers handle failures?
- As `Result` values — each fallible call returns one, and the caller matches or propagates it.
- What does Checked Arithmetic Instead Of Overflow Panics print when run?
- The script runs standalone; its 5 labeled outputs include `total:`, `checked_add at max:`, `saturating_add:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.