Integer types let you store whole numbers in your program. They help you work with counts, ages, or any number without fractions.
0
0
Integer types in Rust
Introduction
Counting items like apples or books
Storing ages or years
Working with indexes in a list
Representing simple scores or points
Syntax
Rust
let variable_name: integer_type = value;
Integer types in Rust include signed (can be negative) and unsigned (only positive) numbers.
Common types: i8, i16, i32, i64, i128 (signed) and u8, u16, u32, u64, u128 (unsigned).
Examples
This creates a signed 32-bit integer named
age with value 30.Rust
let age: i32 = 30;This creates an unsigned 8-bit integer named
count with the max value 255.Rust
let count: u8 = 255;This creates a signed 16-bit integer named
temperature with a negative value.Rust
let temperature: i16 = -10;Sample Program
This program stores counts of fruits using unsigned integers and a temperature using a signed integer. It then prints the results.
Rust
fn main() {
let apples: u8 = 10;
let oranges: u8 = 20;
let total_fruits: u8 = apples + oranges;
println!("Total fruits: {}", total_fruits);
let temperature: i32 = -5;
println!("Temperature: {} degrees", temperature);
}OutputSuccess
Important Notes
Use signed integers (i8, i16, etc.) when you need negative numbers.
Use unsigned integers (u8, u16, etc.) when you only need zero or positive numbers.
Choosing the right size (8, 16, 32, 64, 128) depends on how big your numbers can get.
Summary
Integer types store whole numbers without decimals.
Signed integers can be negative; unsigned cannot.
Pick the size and sign based on your number needs.