Rust Vectors
🦀 Rust Vectors (Vec<T>)
They are growable arrays stored on the heap, perfect when the size of data is not known at compile time.
1. What Is a Vector?
A Vec<T>:
-
Stores elements of the same type
-
Is dynamic (can grow/shrink)
-
Lives on the heap
-
Follows ownership & borrowing rules
2. Creating a Vector
▶️ Empty vector
▶️ Using vec! macro
3. Adding and Removing Elements
4. Accessing Vector Elements
▶️ Using Index (⚠️ Risky)
❌ Panic if index is invalid.
▶️ Using get() (Safe ✅)
✔ Preferred way
5. Iterating Over Vectors
▶️ Read-only iteration
▶️ Mutable iteration
▶️ Taking ownership (rare)
6. Vector Length & Capacity
✔ Capacity optimization improves performance
7. Vectors and Ownership
✔ Avoid move using references:
8. Vectors of Strings
9. Removing by Index
10. Common Vector Methods
| Method | Purpose |
|---|---|
push() |
Add element |
pop() |
Remove last |
get() |
Safe access |
remove() |
Remove by index |
len() |
Size |
is_empty() |
Check empty |
clear() |
Remove all |
11. Vector vs Array
| Feature | Array | Vector |
|---|---|---|
| Size | Fixed | Dynamic |
| Memory | Stack | Heap |
| Growable | ❌ | ✔ |
| Flexibility | Low | High |
❌ Common Mistakes
-
Using index access blindly
-
Ignoring ownership rules
-
Modifying vector while iterating incorrectly
-
Confusing
Vec<T>with&[T]
🧠 Key Takeaways
-
Vec<T>is the go-to collection -
Use
get()for safety -
Prefer borrowing
&Vec<T> -
Heap allocated, dynamic, fast
-
Ownership rules still apply
