Integer overflow in Rust
Rust will not let an overflow slide: pick the behavior you want explicitly.
fn main() {
let big: u8 = 250;
println!("{:?}", big.checked_add(10));
println!("{}", big.saturating_add(10));
println!("{}", big.wrapping_add(10));
let (sum, carried) = big.overflowing_add(10);
println!("{sum} carried={carried}");
println!("{} {}", u8::MAX, i32::MIN);
}
How it works
checked_*returnsNoneinstead of wrapping.saturating_*clamps at the type's limit.wrapping_*is the two's-complement wrap, opted into by name.
Keywords and builtins used here
fni32letmainu8
The run, in numbers
- Lines
- 10
- Characters to type
- 271
- Tokens
- 91
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 68 seconds.
Step 4 of 6 in Variables & types, step 4 of 39 in Language basics.