Rust Arrays
An array is a fixed-size list of values that all have the same type. The values sit next to each other in memory, which makes arrays very fast to read. Because the length is part of the type, it can never change after the array is created.
Creating an array
Write the values inside square brackets, separated by commas. Rust works out the type and length for you, or you can write them yourself as [type; length].
fn main() {
let temps = [18, 21, 19, 24]; // type inferred: [i32; 4]
let grades: [char; 3] = ['A', 'B', 'A']; // type written out
let zeros = [0; 5]; // five copies of 0
println!("{:?}", temps);
println!("{:?}", grades);
println!("{:?}", zeros);
}[18, 21, 19, 24]
['A', 'B', 'A']
[0, 0, 0, 0, 0]
The [value; count] form is handy for creating a buffer filled with a starting value.
Reading and changing elements
Elements are numbered from 0. Use array[index] to read one. To change an element, the array must be declared with mut.
fn main() {
let mut seats = ["free", "free", "free"];
println!("Seat 0 is {}", seats[0]);
seats[1] = "taken";
println!("Seats now: {:?}", seats);
println!("Number of seats: {}", seats.len());
}Seat 0 is free
Seats now: ["free", "taken", "free"]
Number of seats: 3
Out-of-bounds access
What happens if you ask for seats[10] on a three-element array? In C that could silently read random memory. Rust always checks the index. If the index is a constant the compiler knows about, it refuses to compile:
fn main() {
let seats = ["free", "free", "free"];
println!("{}", seats[10]);
}error: this operation will panic at runtime
--> src/main.rs:3:20
|
3 | println!("{}", seats[10]);
| ^^^^^^^^^ index out of bounds: the length is 3 but the index is 10If the index is only known at runtime, the program stops with a panic instead of reading invalid memory. To ask safely, use .get(i), which returns an Option — Some(value) or None:
fn main() {
let seats = ["free", "taken", "free"];
match seats.get(1) {
Some(s) => println!("Seat 1: {}", s),
None => println!("No seat 1"),
}
match seats.get(10) {
Some(s) => println!("Seat 10: {}", s),
None => println!("No seat 10"),
}
}Seat 1: taken
No seat 10
Looping over an array
A for loop visits each element in order. Use .iter().enumerate() when you also want the index.
fn main() {
let scores = [72, 95, 88, 61];
let mut total = 0;
for (i, score) in scores.iter().enumerate() {
println!("Test {}: {}", i + 1, score);
total += score;
}
println!("Average: {}", total / scores.len() as i32);
println!("Best: {}", scores.iter().max().unwrap());
}Test 1: 72
Test 2: 95
Test 3: 88
Test 4: 61
Average: 79
Best: 95
Useful array methods
| Method | What it does | Example result for [3, 1, 2] |
|---|---|---|
len() |
number of elements | 3 |
contains(&x) |
is x in the array? |
contains(&2) → true |
first() / last() |
first / last element as Option |
Some(3) / Some(2) |
iter().sum::<i32>() |
add everything up | 6 |
sort() |
sort in place (needs mut) |
[1, 2, 3] |
reverse() |
reverse in place (needs mut) |
[2, 1, 3] |
Slices: borrowing part of an array
A slice &arr[start..end] is a view into a section of an array without copying it. The start is included, the end is excluded. Functions that take &[T] work with arrays of any length and with vectors.
fn sum(values: &[i32]) -> i32 {
values.iter().sum()
}
fn main() {
let mut data = [9, 4, 7, 1, 8, 2];
data.sort();
println!("Sorted: {:?}", data);
println!("Middle part: {:?}", &data[2..4]);
println!("Sum of all: {}", sum(&data));
println!("Sum of first three: {}", sum(&data[..3]));
}Sorted: [1, 2, 4, 7, 8, 9]
Middle part: [4, 7]
Sum of all: 31
Sum of first three: 7
Tip: Write functions that accept
&[T]instead of&[T; 4]or&Vec<T>. Slices are more flexible and accept both arrays and vectors.
Arrays vs vectors
Use an array when the number of elements is fixed and known in advance (months of the year, RGB components, a chess board row). If you need to add or remove items, use a Vec, covered in the next lesson.
Test yourself
What does [1; 4] create?
- An array with one element, 4
- An array
[1, 1, 1, 1] - An array
[1, 2, 3, 4] - A compile error
What does arr.get(10) return on a 3-element array?
- 0
- A panic
- None
- The last element
Given let a = [10, 20, 30, 40];, what is &a[1..3]?
- [10, 20, 30]
- [20, 30]
- [20, 30, 40]
- [10, 20]