Rust Arrays

🦀 Rust Arrays

In Rust, arrays are collections of elements with:
  • 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

fn main() {
let numbers: [i32; 5] = [10, 20, 30, 40, 50];
println!("{}", numbers[0]);
}

Syntax

let name: [type; size] = [values];

🔹 2. Type Inference

Rust can infer the type and size.

let arr = [1, 2, 3, 4];

🔹 3. Accessing Array Elements

let a = [5, 10, 15];
println!("{}", a[1]); // 10

⚠️ Out-of-bounds access is not allowed

// println!("{}", a[5]); ❌ compile-time / runtime panic

Rust prevents buffer overflow.


🔹 4. Mutable Arrays

Arrays are immutable by default.

fn main() {
let mut nums = [1, 2, 3];
nums[0] = 10;
println!("{:?}", nums);
}

🔹 5. Initialize Array with Same Value

let zeros = [0; 5];

➡️ Creates: [0, 0, 0, 0, 0]


🔹 6. Array Length

let a = [1, 2, 3, 4];
println!("{}", a.len());

🔹 7. Looping Through Arrays

▶️ Using for loop (Recommended)

let nums = [10, 20, 30];

for n in nums {
println!(“{}”, n);
}


▶️ Using index

for i in 0..nums.len() {
println!("{}", nums[i]);
}

🔹 8. Arrays and Ownership

Arrays of Copy types behave safely.

let a = [1, 2, 3];
let b = a;
println!(“{:?}”, a); // OK
println!(“{:?}”, b);

✔ Because i32 is a Copy type


🔹 9. Passing Arrays to Functions

▶️ By reference (Best Practice)

fn print_array(arr: &[i32]) {
println!("{:?}", arr);
}
fn main() {
let a = [1, 2, 3];
print_array(&a);
}

✔ No ownership move
✔ Efficient & safe


🔹 10. Multidimensional Arrays

let matrix: [[i32; 3]; 2] = [
[1, 2, 3],
[4, 5, 6],
];
println!(“{}”, matrix[1][2]); // 6

🔹 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

You may also like...