Sub topic 12
Arrays of arrays
This chapter assumes you can declare and index a one-dimensional array and that you know what [value; N] means. It also assumes you can borrow with & and &mut. Here you will build two-dimensional grids from arrays, read the type annotations, and avoid the usual mistakes with initialization and copying.
What an array of arrays is
An array holds elements of one type, and that type can itself be an array. So [[i32; 3]; 2] is an array of 2 elements, and each element is an array of 3 i32 values. Read the type from the outside in: the outer length comes last.
| Type | Outer length | Inner length | Common reading |
|---|---|---|---|
| `[[i32; 3]; 2]` | 2 | 3 | 2 rows, 3 columns |
| `[[f64; 5]; 4]` | 4 | 5 | 4 rows, 5 columns |
| `[[[u8; 2]; 3]; 4]` | 4 | 3, then 2 | 4 layers of 3 rows of 2 cells |
Rust has no special matrix type here. A "row" is simply the inner array, and "rows and columns" is a convention you choose. The language only knows about arrays inside arrays.
Creating and indexing a grid
You can write a grid literally, or build one filled with a single value by repeating the repeat expression:
fn main() {
let mut grid: [[i32; 3]; 2] = [[0; 3]; 2];
grid[1][2] = 7;
println!("{:?}", grid);
println!("{} rows, {} columns", grid.len(), grid[0].len());
println!("{:?}", grid.get(5).and_then(|row| row.get(0)));
}This prints:
[[0, 0, 0], [0, 0, 7]]
2 rows, 3 columns
None[[0; 3]; 2] first builds the inner array [0; 3], then repeats it twice. In grid[1][2], the first index picks the row and the second picks the cell in that row.
Indexing follows the same rules as for flat arrays. If either index is out of range, grid[r][c] panics at run time. When an index comes from outside your program, use get on each level. Chaining with and_then returns None if either level is out of range.
Iterating over rows and cells
Iterating a grid is two nested iterations. The outer loop yields rows, and the inner loop yields cells. With iter_mut at both levels you can change every cell in place:
fn main() {
let mut grid: [[i32; 3]; 2] = [[1, 2, 3], [4, 5, 6]];
for row in grid.iter_mut() {
for cell in row.iter_mut() {
*cell *= 10;
}
}
println!("{:?}", grid);
let total: i32 = grid.iter().flatten().sum();
println!("{total}");
let mut copy = grid[0];
copy[0] = -1;
println!("{:?} {:?}", copy, grid[0]);
}The output is:
[[10, 20, 30], [40, 50, 60]]
210
[-1, 20, 30] [10, 20, 30]Three points from this program:
grid.iter().flatten()walks every cell in row order, so you can sum or search the whole grid without nested loops.let mut copy = grid[0];copies the row, because[i32; 3]isCopy. Changingcopyleavesgriduntouched. To change the row inside the grid, borrow it withlet row = &mut grid[0];.- When you pass a row to a function, pass a slice (
&grid[0]) so the function accepts a row of any length.
fn row_sums(grid: &[[i32; 3]; 2]) -> [i32; 2] {
let mut sums = [0; 2];
for (i, row) in grid.iter().enumerate() {
sums[i] = row.iter().sum();
}
sums
}
fn print_row(row: &[i32]) {
println!("{:?}", row);
}
fn main() {
let grid = [[1, 2, 3], [4, 5, 6]];
println!("{:?}", row_sums(&grid));
print_row(&grid[1]);
}This prints [6, 15] and then [4, 5, 6]. row_sums fixes both dimensions in its signature. Any other grid size would be a type error. Writing code that works for any size needs const generics, which a later chapter covers.
Initializing grids of non-Copy values
The [value; N] form copies value into every slot, so the element type must be Copy. A Vec or a String is not, which means this does not compile:
// error: the trait bound `Vec<u32>: Copy` is not satisfied
let buckets = [Vec::<u32>::new(); 3];Use std::array::from_fn, which calls a closure once per index:
fn main() {
let mut buckets: [Vec<u32>; 3] = std::array::from_fn(|_| Vec::new());
buckets[1].push(42);
println!("{:?}", buckets);
let table: [[usize; 4]; 3] = std::array::from_fn(|r| std::array::from_fn(|c| r * 4 + c));
println!("{:?}", table);
}The first print shows [[], [42], []]. The second shows [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]. The closure can use the index, so from_fn is also a convenient way to build a table from a formula.
Rectangular only
Every row in [[T; C]; R] has exactly C cells. A grid whose rows have different lengths cannot be this type. The options are:
[&[T]; R], an array of slices that borrows rows of different lengths from elsewhere.Vec<Vec<T>>, when you need to own rows whose lengths are only known at run time.- A flat
[T; R * C]orVec<T>with index arithmetic (row * cols + col), when you want one block of memory.
Memory layout and size
The rows of an array of arrays sit one after another in a single block of memory, with no pointers between them. A [[u8; 4]; 3] occupies 12 bytes, and grid[1][0] is the fifth byte. This makes row-by-row traversal cache-friendly. Looping over columns in the outer loop jumps across rows and is usually slower on large grids.
The size is also the main risk. An array lives wherever its variable lives, which is normally the stack. A [[u8; 1024]; 1024] is 1 MiB, and several of them can overflow a thread's stack. Put large grids in a Vec, or in a Box if you need a fixed shape.
Common errors
- Swapping the dimensions.
[[i32; 3]; 2]has 2 rows and 3 columns, sogrid[2][0]panics even though the type mentions a 3. - Using
[Vec::new(); N]or[String::new(); N]. Usestd::array::from_fn, as above. - Expecting
let row = grid[0];to alias the row. ForCopyelements it makes an independent copy. - Indexing with an unchecked external value. Use
getat each level when the index is not under your control.
Exercise
A 4-row, 5-column grid of f64 values is stored in a variable named grid. What is its type, how do you read the cell in row 2, column 3, and how do you create one filled with 0.0?
Show answer
The type is [[f64; 5]; 4], because the outer length is the number of rows. The cell is grid[2][3]. A zero-filled grid is [[0.0; 5]; 4]. Both indices are zero-based, so row 2 is the third row.
Exercise
Why does let lists = [Vec::<i32>::new(); 3]; fail to compile, and what is a working replacement?
Show answer
The repeat form [value; N] copies the value into each slot, so the element type must be Copy, and Vec<i32> is not. Use let lists: [Vec<i32>; 3] = std::array::from_fn(|_| Vec::new());, which builds a fresh Vec for each slot.