September 28, 2025
Think of a warehouse with a row of identical shelves, each slot numbered and just large enough to hold a single item type. Once these shelves are installed, the capacity is fixed — much like a Rust array, which has a type and a size determined at compile time.^3
In Rust, declaring an array is straightforward:
fn main() {
let shelves: [i32; 5] = [100, 101, 102, 103, 104];
println!("Third shelf holds: {}", shelves[^2]);
}
Every array in Rust is stored in a contiguous memory region on the stack, ensuring both speed and spatial locality. The entire array is tightly packed, mirroring the warehouse scenario where every shelf is right next to the last.^4^6
Below is a Mermaid diagram representing an array as adjacent storage shelves. Each shelf (array slot) is fixed and can be randomly accessed by its index.
graph LR
Shelf0["Shelf 0<br>100"]
Shelf1["Shelf 1<br>101"]
Shelf2["Shelf 2<br>102"]
Shelf3["Shelf 3<br>103"]
Shelf4["Shelf 4<br>104"]
Shelf0 --> Shelf1 --> Shelf2 --> Shelf3 --> Shelf4
Each "Shelf" in the diagram represents one slot in the array, with the number and its contents labeled. The left-to-right sequence matches the in-memory order in Rust. In this diagram, each node represents a storage slot (array index) and holds one item. The physical order in memory is exactly the logical order, matching the warehouse's neat alignment.
Arrays in Rust are always stored contiguously on the stack (when their size is known at compile time and not too large for the stack). Here’s a textual illustration:
let numbers: [u8; 4] = [10, 20, 30, 40];
Memory (stack):
| Address | Value | | :-- | :-- | | ... | ... | | 0x100 | 10 | | 0x101 | 20 | | 0x102 | 30 | | 0x103 | 40 |
Each number occupies a consecutive memory cell, just like items on consecutive shelves.^5
Arrays work seamlessly with slicing and iterators:
let arr = [1, 2, 3, 4, 5];
let slice = &arr[1..4]; // shelves 1, 2, 3
for item in slice {
println!("{}", item);
}
Here, the worker inspects several adjacent shelves using a single pass through indices.
Arrays, much like warehouse shelves, are the backbone of efficient, organized storage when regularity and predictable size matter. Their memory layout in Rust enforces safety and performance, providing a perfect foundation for systems programming and beyond. ^10^12^14^16^18^20^8