Skip to main content

Numbers, overflow and casting

Rust has sized integer types (`i8` through `i128`, `u8` through `u128`, plus `isize`/`usize`) and two float types (`f32`, `f64`). The default is `i32` for integers and `f64` for floats.

There is no implicit conversion anywhere. Mixing a `u8` and an `i32` in an expression is a compile error until you write the conversion out with `as` or with `try_into()`. That verbosity is the point: silent widening and truncation are a classic source of production bugs.

Overflow is not ignored either. In a debug build an overflowing add panics; in a release build it wraps. When you actually want one of those behaviours, ask for it by name with `wrapping_add`, `checked_add` or `saturating_add`.

Mixing integer types

fn main() {
    let a: u8 = 5;
    let b: i32 = 10;
    println!("{}", a + b); // error[E0308]
}

error[E0308]: mismatched types: expected `u8`, found `i32`

Convert one side: `a as i32 + b`. For conversions that can lose data, prefer `i32::try_from(a)` so the failure case is visible.

Run it and change it

The editor below is live: edit anything and the real compiler output updates by itself.

Your Rust