Fundamentals 6 min read

Master Rust Arrays: Declaration, Access, Iteration, and Advanced Uses

Explore Rust arrays in depth—from declaration syntax and element access to iteration, mutable updates, built‑in methods, multidimensional structures, and a practical fixed‑size stack implementation—highlighting their performance‑focused design and safety guarantees for system programming.

Architecture Development Notes
Architecture Development Notes
Architecture Development Notes
Master Rust Arrays: Declaration, Access, Iteration, and Advanced Uses

Declaration of Arrays

In Rust, an array is declared with the syntax let array_name: [type; size] = [elements];, where type is the element type, size is a compile‑time constant, and elements are the initial values. let numbers: [i32; 5] = [1, 2, 3, 4, 5]; The variable numbers holds five 32‑bit integers.

Accessing Array Elements

Elements are accessed by zero‑based indexing, e.g.:

let first_element = numbers[0];
println!("First element is: {}", first_element);

Out‑of‑bounds indexing causes a runtime panic.

Iterating Over an Array

Use a for loop with .iter() to traverse all elements:

for &num in numbers.iter() {
    println!("{}", num);
}

The iter() method returns an iterator over the array.

Array Initialization with Repeated Values

You can create an array filled with the same value using the [value; count] syntax:

let zeros = [0; 10]; // ten zeros

Modifying Array Elements

Arrays are immutable by default; declare them as mutable to change elements:

let mut numbers: [i32; 5] = [1, 2, 3, 4, 5];
numbers[0] = 10;

Array Methods and Properties

len()

: returns the length of the array.

println!("Length: {}", numbers.len());
is_empty()

: checks whether the array is empty.

println!("Is empty: {}", numbers.is_empty());

Multidimensional Arrays

Rust also supports multidimensional arrays, such as a 2×3 matrix:

let matrix: [[i32; 3]; 2] = [[1, 2, 3], [4, 5, 6]];

Extended Example: Implementing a Simple Fixed‑Size Stack

The following example shows a generic FixedStack struct that uses a fixed‑size array for storage and provides push and pop operations:

struct FixedStack<T, const N: usize> {
    data: [T; N],
    top: usize,
}

impl<T, const N: usize> FixedStack<T, N> {
    pub fn new(default: T) -> Self {
        FixedStack { data: [default; N], top: 0 }
    }

    pub fn push(&mut self, item: T) {
        if self.top < N {
            self.data[self.top] = item;
            self.top += 1;
        }
    }

    pub fn pop(&mut self) -> Option<T>
    where
        T: Copy,
    {
        if self.top > 0 {
            self.top -= 1;
            Some(self.data[self.top])
        } else {
            None
        }
    }
}

This demonstrates how arrays enable efficient, safe data structures in Rust.

Rust arrays combine simplicity, safety, and performance, making them a powerful tool for system‑level programming.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

RustSystem ProgrammingData StructuresTutorialArrays
Architecture Development Notes
Written by

Architecture Development Notes

Focused on architecture design, technology trend analysis, and practical development experience sharing.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.