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.
Creating an array
Section titled “Creating an array”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.
You can also let Rust infer the type and just write the values:
let numbers = [1, 2, 3, 4, 5];Same value, repeated
Section titled “Same value, repeated”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);}Accessing elements
Section titled “Accessing elements”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());}Out-of-bounds access is caught
Section titled “Out-of-bounds access is caught”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 10Looping over an array
Section titled “Looping over an array”fn main() { let numbers = [10, 20, 30];
for n in numbers { println!("{n}"); }}Arrays of arrays (2D arrays)
Section titled “Arrays of arrays (2D arrays)”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: 21grid[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.
Arrays vs vectors
Section titled “Arrays vs vectors”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.
Practice
Section titled “Practice”1. Sum and average
Section titled “1. Sum and average”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: 108Average: 18.00Without 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.
2. The hottest day
Section titled “2. The hottest day”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: 31Starting 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 withgrid[row][column]. - If you need to resize, use a
Vecinstead.
Quick check
Section titled “Quick check”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
Read more
Section titled “Read more”- The Array Type — The Rust Book: the official introduction to arrays, including why the length is part of the type.
- Arrays and Slices — Rust by Example: short runnable examples, plus a first look at slices.
- Looping Through a Collection with
for— The Rust Book: why aforloop is safer than walking an array with an index. array— standard library docs: what arrays can do, likemapandas_slice, and how they borrow all the slice methods too.