Rust Arrays
🦀 Rust Arrays
-
Fixed size
-
Same data type
-
Stored on the stack
They are fast, safe, and commonly used when the size is known at compile time.
🔹 1. Declaring an Array
Syntax
🔹 2. Type Inference
Rust can infer the type and size.
🔹 3. Accessing Array Elements
⚠️ Out-of-bounds access is not allowed
Rust prevents buffer overflow.
🔹 4. Mutable Arrays
Arrays are immutable by default.
🔹 5. Initialize Array with Same Value
➡️ Creates: [0, 0, 0, 0, 0]
🔹 6. Array Length
🔹 7. Looping Through Arrays
▶️ Using for loop (Recommended)
▶️ Using index
🔹 8. Arrays and Ownership
Arrays of Copy types behave safely.
✔ Because i32 is a Copy type
🔹 9. Passing Arrays to Functions
▶️ By reference (Best Practice)
✔ No ownership move
✔ Efficient & safe
🔹 10. Multidimensional Arrays
🔹 11. Arrays vs Vectors (Important)
| Feature | Array | Vector |
|---|---|---|
| Size | Fixed | Dynamic |
| Memory | Stack | Heap |
| Growable | ❌ | ✔ |
| Use case | Known size | Unknown size |
👉 If size is dynamic → use Vec<T>
❌ Common Mistakes
-
Expecting arrays to grow
-
Out-of-bounds indexing
-
Confusing arrays with vectors
-
Forgetting arrays are stack-allocated
🧠 Key Takeaways
-
Arrays are fixed-size
-
Stored on the stack
-
Fast and memory-safe
-
Best when size is known
-
Use slices (
&[T]) for flexibility
