🎓 A1Learner
🔍
0 of 142 lessons completed

Rust Nested Arrays

A nested array is an array whose values are arrays. The whole shape is a grid with rows and columns.

A grid is an array of arrays

Each value in the outer array is a whole row:

let grid = [[1, 2, 3], [4, 5, 6]];
println!("rows = {}", grid.len());

Reach one item with two indexes

grid[1][2] walks in twice: row 1 first, then position 2 inside that row. Counting starts at 0, twice:

let grid = [[1, 2, 3], [4, 5, 6]];
println!("grid[1][2] = {}", grid[1][2]);

A whole row is a value too

grid[0] is the complete first row. It is an [i32; 3]. You can print it. You can pass it to a function:

let grid = [[1, 2, 3], [4, 5, 6]];
let first = grid[0];
println!("{:?}", first);

Two loops visit every item

The outer loop hands over one row at a time. The inner loop walks that row:

let grid = [[1, 2], [3, 4]];
let mut sum = 0;
for row in grid { for n in row { sum += n; } }
println!("sum = {sum}");

Example

fn transpose(matrix: [[i32; 3]; 3]) -> [[i32; 3]; 3] {
    let mut result = [[0; 3]; 3];
    for r in 0..3 {
        for c in 0..3 {
            result[c][r] = matrix[r][c];
        }
    }
    result
}
fn main() {
    let grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
    println!("grid[1][2] = {}", grid[1][2]);
    let flipped = transpose(grid);
    for row in flipped {
        println!("{:?}", row);
    }
}

Key points

  • Read the type from the inside out.
  • [[i32; 3]; 2] means 2 rows.
  • Each row is an [i32; 3].
  • That is 3 numbers in a row
  • Every row must have the same length.
  • The type fixes the shape.
  • So a nested array is always a tidy rectangle

In this example, grid is a 3 by 3 nested array: three rows of three numbers. grid[1][2] walks in twice: row 1 is [4, 5, 6], and position 2 inside it is 6. The transpose function turns rows into columns. It builds a fresh grid of zeros, then copies every item to the swapped position: result[c][r] = matrix[r][c]. The printed rows of flipped show the old first column — 1, 4, 7 — now standing as the first row.

Note

The shape is part of the type.

A plain array length works the same way.

A [[i32; 3]; 2] is one type.

A [[i32; 3]; 3] is another type.

They are different types.

They cannot be mixed.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

If grid is [[10, 20], [30, 40]], what is grid[1][0]?