🎓 A1Learner
🔍

Rust Arrays

An array is a fixed number of values of the same type, stored side by side. Every value sits in its own numbered slot.

Build an array two ways

List the values, or repeat one value to fill the slots. len() asks how many items the array holds:

let days = ["Mon", "Tue", "Wed"];
let grid = [0; 4];
println!("{} {:?}", days.len(), grid);

Read an item by its position

Counting starts at 0, so a[0] is the first item:

let a = [10, 20, 30];
println!("first = {} last = {}", a[0], a[2]);

A safer read with get

Reading past the end with a[i] stops the program. a.get(i) answers with an Option instead — Some with the item, or None:

let a = [10, 20, 30];
println!("{:?} {:?}", a.get(1), a.get(9));

An array's size in bytes

The items sit side by side in one block on the stack. size_of_val reports the whole block: five i32 values at 4 bytes each:

let a = [0i32; 5];
println!("{} bytes", std::mem::size_of_val(&a));

An array may be empty

Zero slots is a legal array. Borrowing it gives an empty slice:

let empty: [u32; 0] = [];
println!("len = {}", empty.len());

Example

fn main() {
    let days = ["Mon", "Tue", "Wed"];
    let grid = [0; 4];
    println!("first = {} days = {}", days[0], days.len());
    println!("grid = {:?} total = {}", grid, days.len() + grid.len());
}

Key points

  • [i32; 3] means: an array of 3 values of type i32 — the size is part of the type
  • If Rust can see a bad index while compiling, it refuses to compile the program.
  • That is a[5] written directly on a 3-item array.
  • A bad index that only appears while running panics instead.

In this example, days is an array of three day names. [0; 4] builds grid by repeating 0 four times. days[0] reads the first item, "Mon". days.len() is 3 and grid.len() is 4, so the total is 7. The {:?} slot prints the whole array at once, which is handy while you are learning.

Note

An [i32; 3] and an [i32; 4] are different types and cannot be mixed directly.

To pass arrays of any size to one function, lend the function a slice, &a[..].

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

What does the expression [7; 3] produce?