typestar

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

  1. checked_* returns None instead of wrapping.
  2. saturating_* clamps at the type's limit.
  3. wrapping_* is the two's-complement wrap, opted into by name.

Keywords and builtins used here

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.

Type this snippet

Step 4 of 6 in Variables & types, step 4 of 39 in Language basics.

← Previous Next →