How to create a 2D matrix in Rust

Learn two methods for dynamically creating a 2D matrix, one using functional programming and the other imperative.

This article shows you two methods for dynamically creating a two-dimensional matrix with the Rust programming language.

If we want to fill up our vector of vectors with a simple constant, such as 0, then there’s not much work to do. We can use a nested call to the vec! macro: vec![vec![0; 16]; 16];. But what should we do if we need to update the contents of the matrix dynamically?

Using an imperative style

The traditional approach is to use two steps. In the first step, you initialize a vector of vectors. or Vec<Vec<T>> in Rust syntax, with a temporary value, such as 0. The second step updates each element with the intended starting value.
				
					fn main() {
    // step 1: initialize with 0
    let mut grid = vec![vec![0; 16]; 16];
    
    // step 2: update each element
    for y in 0..grid.len() {
        for x in 0..grid.len() {
            grid[x][y] = x * y;
        }
    }

    println!("{grid:?}")
}

				
			

Using a functional style with iterators and ranges

For those programmers who prefer a more functional style, ranges and iterators are available to you. Notice that you will need use nested calls to map and declare the type explicitly.

This style allows for the matrix to be created in a single pass, by applying a closure, also known as an anonymous function or lambda function during the creation step.

				
					fn main() {
    let grid: Vec<Vec<_>> = (0..16).map(|x| {
            (0..16).map(|y| x * y).collect()
        }).collect();

    println!("{grid:?}")
}
				
			

Which approach should you use?

The traditional style is simpler to read. This is a large bonus. It’s also more familiar to programmers that have a background in object-oriented and imperative languages.

The functional style allows for more aggressive optimization by the compiler. Because it has nearly full control over how to perform what’s being asked of it, it can update more than one element at a time via auto-vectorization.

Contents