Rust Data Structures
🦀 Rust Data Structures
Rust’s data structures are safe, fast, and tightly integrated with ownership & borrowing.
🔹 Classification of Rust Data Structures
Rust data structures can be divided into three main categories:
1️⃣ Primitive / Built-in
2️⃣ Standard Library Collections
3️⃣ User-Defined Data Structures
1. Primitive / Built-in Data Structures
▶️ Arrays ([T; N])
Fixed-size, same data type.
✔ Stored on stack
❌ Size cannot change
▶️ Tuples (( ))
Fixed-size, different data types.
✔ Lightweight
✔ Useful for returning multiple values
2. Standard Library Collections (Most Important)
These are stored on the heap and can grow or shrink.
▶️ Vector (Vec<T>)
Dynamic array (most used).
Or:
✔ Growable
✔ Fast
✔ Indexing + iteration
▶️ String (String)
Growable UTF-8 text data.
✔ Heap allocated
✔ UTF-8 safe
▶️ HashMap (HashMap<K, V>)
Key-value storage.
✔ Fast lookup
✔ No duplicate keys
▶️ HashSet (HashSet<T>)
Stores unique values only.
▶️ VecDeque (VecDeque<T>)
Double-ended queue.
3. User-Defined Data Structures
▶️ Struct
Used to group related data.
✔ Similar to C structs
✔ Very common in Rust
▶️ Enum
Used to represent multiple states.
✔ Extremely powerful
✔ Used with match
▶️ Struct + Enum (Real-World Rust Style)
🔹 Stack vs Heap (Data Structure Perspective)
| Stack | Heap |
|---|---|
| Fixed size | Dynamic size |
| Faster | Slightly slower |
| Arrays, tuples | Vec, String, HashMap |
🔹 Ownership with Data Structures
✔ Use references to avoid move:
🔹 Common Rust Data Structures (Quick Table)
| Structure | Use Case |
|---|---|
| Array | Fixed-size data |
| Tuple | Mixed data |
| Vec | Dynamic list |
| String | Text |
| HashMap | Key-value |
| HashSet | Unique values |
| Struct | Custom objects |
| Enum | State modeling |
🧠 Key Takeaways
-
Rust data structures are memory-safe
-
Heap structures follow ownership rules
-
VecandHashMapare most used -
struct+enum= idiomatic Rust -
Compiler prevents invalid access
