🦀 Rust Data Types Explained
Introduction
Every value in Rust has a type, known at compile time.
(Compile time is when your code is translated into machine language.)
Rust is a statically typed language, meaning you usually define the type of each variable.
However, the compiler can often infer types — it looks at how you use the variable and guesses the type for you.
Two Main Categories of Types
1. Scalar Types (Single Values)
Scalar types store one value.
Integers: Whole numbers, like
1,2,-3.Signed: can be negative (
-5)Unsigned: only positive (
5)
Floats: Numbers with a decimal point, like
3.5or10.0.Booleans: Only two choices:
trueorfalse.Characters: A single letter or emoji, like
'A'or'c'.
2. Compound Types (Multiple Values)
Compound types combine multiple values.
Array
An array is a fixed list of values, all of the same type, stored in order.
let numbers: [i32; 3] = [1, 2, 3]; // always 3 items
Fixed size — cannot add or remove elements.
Stored directly on the stack.
Slice
A slice is a reference to part of an array.
Does not own data; just borrows it.
Type does not include length:
[T]or&[T].let arr = [1, 2, 3, 4, 5];let slice: &[i32] = &arr[1..4]; // points to [2, 3, 4]
Tuple
A tuple is a group of values, where each value can have a different type.
let tuple: (bool, u32, f64) = (true, 2, 3.0);
Struct
A struct lets you group related values together, and each value has a name.
struct Person {
age: u32,
height: f64,
}
let p = Person { age: 25, height: 1.75 };
Enum
An enum defines a type that can be one of several variants.
enum Direction {
North,
South,
East,
West,
}
let d = Direction::East; // only one variant can be used at a time
Useful for fixed sets of choices.
Advanced Compound Types
Tuple Struct
A tuple struct is like a named tuple.
struct Color(i32, i32, i32); // tuple struct with 3 fields
let red = Color(255, 0, 0);
Type Alias
A type alias gives an existing type a new name.
type Point = (i32, i32);
let p: Point = (3, 4); // same as a tuple, just easier to read
Summary
Tuple → unnamed group of values.
Tuple struct → named tuple that creates a new type.
Type alias (
type) → gives an existing type a new name but doesn’t create a new type.Array → fixed-size collection of same-type values.
Slice → reference to part of an array (dynamic size).
Struct → named fields, each can have its own type.
Enum → one choice from a fixed set of variants.

