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.
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.
<code>let numbers: [i32; 5] = [1, 2, 3, 4, 5];</code>The variable numbers holds five 32‑bit integers.
Accessing Array Elements
Elements are accessed by zero‑based indexing, e.g.:
<code>let first_element = numbers[0];
println!("First element is: {}", first_element);</code>Out‑of‑bounds indexing causes a runtime panic.
Iterating Over an Array
Use a for loop with .iter() to traverse all elements:
<code>for &num in numbers.iter() {
println!("{}", num);
}</code>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:
<code>let zeros = [0; 10]; // ten zeros</code>Modifying Array Elements
Arrays are immutable by default; declare them as mutable to change elements:
<code>let mut numbers: [i32; 5] = [1, 2, 3, 4, 5];
numbers[0] = 10;</code>Array Methods and Properties
len() : returns the length of the array.
<code>println!("Length: {}", numbers.len());</code>is_empty() : checks whether the array is empty.
<code>println!("Is empty: {}", numbers.is_empty());</code>Multidimensional Arrays
Rust also supports multidimensional arrays, such as a 2×3 matrix:
<code>let matrix: [[i32; 3]; 2] = [[1, 2, 3], [4, 5, 6]];</code>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:
<code>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
}
}
}
</code>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.
Architecture Development Notes
Focused on architecture design, technology trend analysis, and practical development experience sharing.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.