5.7 Overflow in Arithmetic Operations
Integer overflow can be a major source of bugs. Rust addresses this issue as follows:
5.7.1 Debug Mode
In debug builds, Rust checks for integer overflow and panics if it occurs:
let x: u8 = 255;
let y = x + 1; // Code like this would panic in debug mode
5.7.2 Release Mode
In release builds, integer overflow wraps around using two’s complement arithmetic by default (e.g., 255 + 1
in an 8-bit type wraps to 0).
5.7.3 Explicit Overflow Handling
If you need a specific overflow behavior in both debug and release modes, Rust provides methods in the standard library:
- Wrapping:
wrapping_add
,wrapping_sub
, etc. - Checked:
checked_add
returnsNone
on overflow. - Saturating:
saturating_add
caps values at the numeric boundary. - Overflowing:
overflowing_add
returns a tuple(result, bool_overflowed)
.