Sub topic 12
Arrays of arrays
This chapter assumes you know how to declare arrays, initialize them with [value; N], and index them. Here we nest arrays to build grids and tables.
The type of a nested array
An array's element type can itself be an array. The type [[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.
fn main() {
let grid: [[i32; 3]; 2] = [[1, 2, 3], [4, 5, 6]];
println!("{}", grid.len());
println!("{}", grid[0].len());
println!("{}", grid[1][2]);
}This prints 2, 3, and 6. The first index picks a row. The second index picks a column inside that row. Each index is bounds-checked on its own.
Initializing a grid
Use [value; N] twice to build a grid filled with one value. The inner expression is evaluated once and copied, so the element type must be Copy.
fn main() {
let mut board = [[0u8; 4]; 3];
board[1][2] = 9;
for row in &board {
println!("{:?}", row);
}
}The output is three lines: [0, 0, 0, 0], [0, 0, 9, 0], and [0, 0, 0, 0]. Because [0u8; 4] is Copy, each row is an independent copy. Changing board[1][2] does not affect the other rows.
Iterating over rows and cells
Iterating over &board yields &[u8; 4], one reference per row. A second loop walks the cells. Use iter_mut when you need to change values.
fn main() {
let mut grid = [[1, 2, 3], [4, 5, 6]];
for row in grid.iter_mut() {
for cell in row.iter_mut() {
*cell *= 10;
}
}
let total: i32 = grid.iter().map(|row| row.iter().sum::<i32>()).sum();
println!("{total}");
}This prints 210. The inner sum adds one row, and the outer sum adds the row totals.
Rows can be slices
A row of a nested array is an array, so &grid[0] coerces to &[i32]. A function that takes a slice can then work on one row without knowing the grid's width.
fn row_sum(row: &[i32]) -> i32 {
row.iter().sum()
}
fn main() {
let grid = [[1, 2, 3], [4, 5, 6]];
println!("{}", row_sum(&grid[1]));
}Common errors
- Confusing the dimensions. In
[[T; COLS]; ROWS], the inner length is the column count. Writing[[0; 2]; 3]gives 3 rows of 2 columns, not the reverse. - Out-of-bounds indexing.
grid[2][0]on a 2-row grid panics at run time. With constant indices the compiler can reject it. Usegrid.get(2).and_then(|row| row.get(0))to get anOption. - Non-
Copyelements.[[String::new(); 3]; 2]does not compile, becauseStringis notCopy. UseVecorstd::array::from_fninstead.
Exercise
What is the type of a grid with 4 rows and 5 columns of f64 values, and what does grid[3][4] refer to?
Show answer
The type is [[f64; 5]; 4]. The expression grid[3][4] refers to the last row's last column, the final element. Both indices are the highest valid ones.
Exercise
Why does let g = [[String::new(); 2]; 2]; fail to compile, and how can you fix it?
Show answer
The [value; N] form copies the value, which requires Copy, and String is not Copy. Build the grid with std::array::from_fn, for example let g: [[String; 2]; 2] = std::array::from_fn(|_| std::array::from_fn(|_| String::new()));. You can also use a Vec<Vec<String>>.