← Back to Rust Course | Chapter 2: Variables & Types | Lesson 5 of 7

Integer Types

Rust has many different sizes of whole numbers so your program only uses as much memory as it truly needs.

Signed vs Unsigned

Signed integer types (i8, i16, i32, i64, i128) can represent negative and positive numbers, while unsigned types (u8, u16, u32, u64, u128) only represent zero and positive numbers, giving them double the positive range for the same bit size.

Example: Signed vs Unsigned

markup
fn main() {
    let signed: i32 = -10;
    let unsigned: u32 = 10;
    println!("signed: {}, unsigned: {}", signed, unsigned);
}

Default Integer Type

When you write an integer literal without an explicit type and the compiler cannot infer one from context, Rust defaults to i32, which is a good general-purpose choice on modern hardware.

Example: Default Integer Type

markup
fn main() {
    let default_int = 100;
    println!("Default integer type holds: {}", default_int);
}

usize for Indexing

usize is an unsigned integer sized to match the machine's pointer width (commonly 64-bit). It is the type Rust uses for array/vector indices and lengths, since a collection can never have a negative size.

Example: usize for Indexing

markup
fn main() {
    let numbers = [10, 20, 30];
    let index: usize = 1;
    println!("Element at index {}: {}", index, numbers[index]);
}

Integer Overflow

Every integer type has a fixed range, and exceeding it is called overflow. In a debug build, Rust panics immediately on overflow to catch the bug early; in a release build it wraps around instead, so relying on overflow behavior is dangerous.

Note: checked_add returns None instead of panicking or wrapping, letting you handle overflow explicitly.

Example: Integer Overflow

markup
fn main() {
    let small: u8 = 250;
    let safe_sum = small.checked_add(3);
    println!("checked_add result: {:?}", safe_sum);
}
Common Mistakes
  1. Using a small integer type like i8 for a value that can exceed its range, causing an overflow panic in debug mode.
  2. Mixing signed and unsigned integer types (like i32 and u32) in an expression without an explicit conversion, which fails to compile.
  3. Assuming integers default to i64 -- Rust actually defaults to i32 when a type cannot otherwise be inferred.
Chapter Summary
  • Integer types are named by signedness and size, e.g. i32 (signed 32-bit) and u8 (unsigned 8-bit).
  • isize/usize are pointer-sized integers, commonly used for indexing collections.
  • Rust defaults an unannotated integer literal to i32 unless context requires otherwise.
  • Arithmetic overflow panics in debug builds and wraps silently in release builds unless handled explicitly.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.