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' 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 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.
- 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.
- 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