Rust Data Structures
Estimated reading: 3 minutes 53 views

🦀 Rust – Arrays: Fixed-Size Collections with Safe Indexing

🧲 Introduction – Why Learn Arrays in Rust?

Arrays are a fundamental data structure used to store a fixed number of elements of the same type. In Rust, arrays are stored on the stack and come with compile-time length checking and safe indexing—no buffer overflows or undefined behavior.

🎯 In this guide, you’ll learn:

  • How to declare and use arrays in Rust
  • How indexing and slicing works
  • How Rust arrays enforce memory safety
  • Practical code examples with outputs and explanations

📦 Declaring an Array

🔹 Code Example:

fn main() {
    let nums = [10, 20, 30, 40, 50];
    println!("First element: {}", nums[0]);
}

🧠 Explanation:

  • let nums = [10, 20, 30, 40, 50]; → Creates a 5-element array of i32
  • nums[0] accesses the first element (zero-based indexing)

📤 Output:

First element: 10

🧾 Specifying Length and Type

🔹 Code Example:

fn main() {
    let nums: [i32; 4] = [1, 2, 3, 4];
    println!("Length: {}", nums.len());
}

🧠 Explanation:

  • [i32; 4] explicitly sets the array type and length
  • .len() returns number of elements

📤 Output:

Length: 4

🔁 Array with Repeated Values

🔹 Code Example:

fn main() {
    let zeros = [0; 5];
    println!("{:?}", zeros);
}

🧠 Explanation:

  • [0; 5] creates an array with five zeros

📤 Output:

[0, 0, 0, 0, 0]

🔍 Indexing and Accessing Elements

🔹 Code Example:

fn main() {
    let primes = [2, 3, 5, 7, 11];

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

📤 Output:

primes[0] = 2
primes[1] = 3
primes[2] = 5
primes[3] = 7
primes[4] = 11

📌 Indexing is checked at runtime. Out-of-bounds access causes a panic, not undefined behavior.


🧩 Array Slicing

🔹 Code Example:

fn main() {
    let data = [10, 20, 30, 40, 50];
    let slice = &data[1..4];

    println!("Slice: {:?}", slice);
}

🧠 Explanation:

  • &data[1..4] → Creates a slice from index 1 to 3 ([20, 30, 40])

📤 Output:

Slice: [20, 30, 40]

⚠️ Safe Indexing Behavior

OperationBehavior
array[index]Panics at runtime if out of bounds
array.get(index)Returns Option<T> (safe)
.len()Returns number of elements
&array[start..end]Creates a slice from array

🔹 Code Example with .get():

fn main() {
    let arr = [1, 2, 3];

    match arr.get(5) {
        Some(value) => println!("Value: {}", value),
        None => println!("Index out of bounds"),
    }
}

📤 Output:

Index out of bounds

🔒 Ownership and Copy Behavior

Rust arrays follow ownership rules:

  • Arrays of Copy types (like i32) can be copied
  • Arrays of String or heap data are moved unless cloned

🔹 Example:

fn main() {
    let a = [String::from("hi"); 2];
    let b = a; // a is now invalid
    // println!("{:?}", a); // ❌ This would cause an error
    println!("{:?}", b);
}

📌 Summary – Recap & Next Steps

Arrays in Rust are fixed-size, efficient, and safe to use. They are ideal for storing stack-based collections when the size is known at compile time.

🔍 Key Takeaways:

  • Arrays have fixed size and type: [T; N]
  • Indexing is safe and checked at runtime
  • Use .get() for optional safe access
  • Slices provide views into arrays without copying

⚙️ Next: Learn about Rust – Vectors to handle dynamic-sized lists on the heap.


❓FAQs


Can arrays grow or shrink in Rust?
❌ No. Arrays have a fixed size. Use Vec<T> (vector) for growable collections.


Is array indexing in Rust zero-based?
✅ Yes. The first element is at index 0.


What happens if I index out of bounds?
✅ The program will panic at runtime with a clear message.


Can I pass an array to a function?
✅ Yes. Use fn foo(arr: [i32; 3]) for fixed-size arrays or &[i32] for slices.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Rust – Arrays

Or Copy Link

CONTENTS
Scroll to Top