Rust by Example: Data Types Overview
A comprehensive overview of Rust's type system. Explore scalar types like integers, floats, booleans, and characters, as well as compound types like tuples and arrays, understanding how Rust enforces type safety at compile time.
Code
fn main() {
// --- Scalar Types ---
// Integers (signed i8-i128, unsigned u8-u128)
let age: u32 = 30;
let temperature: i32 = -5;
// Floating-point numbers (f32, f64)
let pi: f64 = 3.14159; // f64 is default
// Booleans
let is_active: bool = true;
// Characters (Unicode Scalar Values, 4 bytes)
let heart_emoji: char = '❤';
// --- Compound Types ---
// Tuples: Fixed size, mixed types
let person: (i32, f64, u8) = (500, 6.4, 1);
let (x, y, z) = person; // Destructuring
println!("Tuple value y: {}", y);
println!("Tuple index 0: {}", person.0);
// Arrays: Fixed size, same type
let months = ["Jan", "Feb", "Mar", "Apr"];
let first_month = months[0];
// Array with type and size
let buffer: [u8; 5] = [0; 5]; // [0, 0, 0, 0, 0]
println!("Buffer: {:?}", buffer);
}Explanation
Rust is a statically typed language, meaning it must know the types of all variables at compile time. While the compiler can usually infer the type based on the value and how it's used, sometimes explicit type annotations are required. Rust's types are divided into two main categories: Scalar types and Compound types.
Scalar types represent a single value:
- Integers: Available in signed (
i8toi128) and unsigned (u8tou128) variants.isizeandusizedepend on the computer's architecture (64-bit on 64-bit systems). - Floats:
f32andf64(default). They follow the IEEE-754 standard. - Booleans:
bool, which is 1 byte in size. - Characters:
charis a unique 4-byte type representing a Unicode Scalar Value. This means it can hold accented letters, Chinese characters, and emojis, not just ASCII.
Compound types group multiple values into one type. Tuples allow you to group together a variety of types into one compound value (e.g., an integer and a float). They are stored contiguously in memory. Arrays contain multiple values of the same type and have a fixed length known at compile time. Arrays are stack-allocated, making them extremely fast but inflexible compared to the heap-allocated Vector.
Code Breakdown
let age: u32 = 30;. Here we explicitly annotate the type as u32 (unsigned 32-bit integer). Without this, Rust would default to i32.let heart_emoji: char = '❤';. Rust chars are specified with single quotes. Because they are 4 bytes, they can hold any Unicode character.(). We can access elements using dot notation person.0 or by destructuring them into individual variables let (x, y, z) = person;.let buffer: [u8; 5] = [0; 5];. This syntax initializes an array of 5 elements, all set to 0. The type annotation [u8; 5] means "an array of u8 with length 5".
