</>
Skip to content
Rust lessons (22/43)

Rust — Arrays

Arrays: fixed length, stack-allocated

let months = ["Jan", "Feb", "Mar", "Apr"];   // type: [&str; 4]
let zeros  = [0; 5];                          // [0,0,0,0,0] — init shorthand

The length is part of the type: [i32; 3] and [i32; 4] are different types entirely. That's why arrays can live on the fast stack — size is known forever at compile time.

Indexing & bounds

let nums = [10, 20, 30];

nums[0];      // 10
nums[2];      // 30

// nums[3]   → PANIC at runtime (index out of bounds) — checked, not UB
nums.get(3);  // Option<&i32> → None — safe variant

Out-of-range indexing panics rather than corrupting memory (C would silently read garbage). .get() returns Option, letting you handle absence gracefully:

match nums.get(5) {
    Some(v) => println!("found {}", v),
    None => println!("no such index"),
}

The type signature [T; N]

let a: [i32; 3] = [1, 2, 3];     // three i32s exactly
let flags = [false; 8];           // eight falses

Functions can demand exact sizes:

fn first_three(items: &[i32; 3]) -> [i32; 3] { *items }

Iterating — always with for

for n in nums {
    println!("{}", n);            // copies each i32 (they're Copy)
}

for m in months {
    println!("{}", m);            // borrows each &str ✓ idiomatic
}

.iter() gives references explicitly:

for n in nums.iter() {
    println!("{}", n);
}

len, slices & mutability

nums.len();                       // 3

let slice = &nums[0..2];          // &[i32] view: [10, 20]
let all: &[i32] = &nums;          // whole array as slice

let mut counters = [0; 3];
counters[0] += 1;                 // needs `mut` on the binding

Arrays vs Vectors vs Slices — decide correctly

TypeSizeWhereUse when
[T; N] arrayfixedstackknown-at-compile-time counts: months, RGB [u8;3], buffers
Vec<T> vectorgrowsheapdynamic lists (the everyday choice)
&[T] sliceborrowed view—function parameters accepting either

Real code is ~90% vectors/slices; pure arrays appear for fixed data like lookup tables:

const DAYS_IN_MONTH: [u32; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

Mini Practice

  1. Build [f64; 12] monthly rainfall; print total via sum().
  2. Trigger index-out-of-bounds panic; then rewrite with .get().
  3. Create [0u8; 64] buffer; set every even index to 1.
  4. Write fn mean(arr: &[f64]) -> f64 handling empty slices.
  5. Explain why [i32; 3] ≠ [i32; 4] in one sentence.

Next: vectors →

Related Topics

Frequently Asked Questions about Arrays

What is Arrays in Rust?

Arrays is a fundamental concept in Rust. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Arrays?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Arrays.

Why is Arrays important in Rust?

Arrays is essential for Rust development. Understanding this concept will help you write better code and solve real-world problems more effectively.