Integer Types
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
fn main() {
let signed: i32 = -10;
let unsigned: u32 = 10;
println!("signed: {}, unsigned: {}", signed, unsigned);
}
Login to try C/C++/Java/PHP code in the editor
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
fn main() {
let default_int = 100;
println!("Default integer type holds: {}", default_int);
}
Login to try C/C++/Java/PHP code in the editor
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
fn main() {
let numbers = [10, 20, 30];
let index: usize = 1;
println!("Element at index {}: {}", index, numbers[index]);
}
Login to try C/C++/Java/PHP code in the editor
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
fn main() {
let small: u8 = 250;
let safe_sum = small.checked_add(3);
println!("checked_add result: {:?}", safe_sum);
}
Login to try C/C++/Java/PHP code in the editor
- Using a small integer type like
i8for a value that can exceed its range, causing an overflow panic in debug mode. - Mixing signed and unsigned integer types (like
i32andu32) in an expression without an explicit conversion, which fails to compile. - Assuming integers default to
i64-- Rust actually defaults toi32when a type cannot otherwise be inferred.
- Integer types are named by signedness and size, e.g.
i32(signed 32-bit) andu8(unsigned 8-bit). isize/usizeare pointer-sized integers, commonly used for indexing collections.- Rust defaults an unannotated integer literal to
i32unless 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: