Skip to content

Rust Arrays

An array is a fixed-size list of values, all of the same type. “Fixed-size” is the key word — once you create an array, it can’t grow or shrink. If you need something that resizes, that’s what a vector is for.

fn main() {
let numbers: [i32; 5] = [1, 2, 3, 4, 5];
println!("{:?}", numbers);
}

The type [i32; 5] reads as “an array of 5 i32 values.” That length is part of the type — a [i32; 5] and a [i32; 3] are considered different types.

▶ Try it Yourself

You can also let Rust infer the type and just write the values:

let numbers = [1, 2, 3, 4, 5];

To fill an array with the same value N times, use this shorthand:

fn main() {
let zeros = [0; 5]; // [0, 0, 0, 0, 0]
println!("{:?}", zeros);
}
▶ Try it Yourself

Arrays are indexed starting at 0, using square brackets:

fn main() {
let fruits = ["apple", "banana", "cherry"];
println!("{}", fruits[0]); // apple
println!("{}", fruits[2]); // cherry
println!("Length: {}", fruits.len());
}
▶ Try it Yourself

Try to access an index that doesn’t exist, and Rust stops your program instead of quietly reading garbage memory:

fn get_fruit(fruits: [&str; 3], index: usize) -> &str {
fruits[index]
}
fn main() {
let fruits = ["apple", "banana", "cherry"];
println!("{}", get_fruit(fruits, 10)); // panics at runtime
}
thread 'main' (12345) panicked at src/main.rs:2:5:
index out of bounds: the len is 3 but the index is 10
fn main() {
let numbers = [10, 20, 30];
for n in numbers {
println!("{n}");
}
}
▶ Try it Yourself

An array can hold other arrays. That gives you a grid with rows and columns, like a game board or a small spreadsheet. The type of grid below is [[i32; 3]; 2], which reads as “2 rows, each an array of 3 i32 values.”

fn main() {
// 2 rows, 3 columns
let grid = [
[1, 2, 3],
[4, 5, 6],
];
println!("Row 1, column 2: {}", grid[1][2]);
let mut total = 0;
for row in grid {
println!("{:?}", row);
for value in row {
total += value;
}
}
println!("Total: {total}");
}

Output:

Row 1, column 2: 6
[1, 2, 3]
[4, 5, 6]
Total: 21
▶ Try it Yourself

grid[1][2] means “row 1, then column 2 inside that row.” Both start counting at 0, so this is the second row, third value. To visit every value, use one loop for the rows and a second loop inside it for the values in each row.

Every row must have the same length, because the row length is part of the type. If you also need each position while looping, .iter().enumerate() gives you the index and the value together. It’s shown on the for loop page.

Use an array when the size is fixed and known upfront (like the seven days of the week). Use a Vec when you need to add or remove items — which, in practice, is most of the time. Arrays are less common in everyday Rust code than vectors are.

Make the array [4, 8, 15, 16, 23, 42]. Add up all the values, then print the sum and the average with two decimal places. Hint: loop with for, keep a running total, and turn both numbers into f64 with as before you divide.

Show solution
fn main() {
let numbers = [4, 8, 15, 16, 23, 42];
let mut total = 0;
for n in numbers {
total += n;
}
let average = total as f64 / numbers.len() as f64;
println!("Sum: {total}");
println!("Average: {average:.2}");
}

Output:

Sum: 108
Average: 18.00
▶ Try it Yourself

Without as f64, total / numbers.len() would be whole-number division, and Rust would also complain that total (an i32) and len() (a usize) are different types.

You have a week of temperatures: [18, 25, 12, 31, 22, 27, 19]. Find and print the highest one. Hint: start with let mut hottest = temps[0];, then loop and replace it whenever you find a bigger value.

Show solution
fn main() {
let temps = [18, 25, 12, 31, 22, 27, 19];
let mut hottest = temps[0];
for t in temps {
if t > hottest {
hottest = t;
}
}
println!("Hottest day: {hottest}");
}

Output:

Hottest day: 31
▶ Try it Yourself

Starting from temps[0] instead of 0 matters: if every temperature were below zero, starting at 0 would give a wrong answer.

  • Arrays have a fixed length that’s part of their type: [i32; 5].
  • Access elements with array[index], starting at 0.
  • Out-of-bounds access panics at runtime instead of causing undefined behavior.
  • Arrays can hold arrays: [[i32; 3]; 2] is a grid you read with grid[row][column].
  • If you need to resize, use a Vec instead.

Quick check

1. What's true about a Rust array's length?

2. What happens when you access an array index that's out of bounds at runtime?

3. What does let zeros = [0; 5]; create?

Score: 0 / 3