Rust, Software Development

Rust – How to create Two-Dimensional Array Example

Rust selection sort EPCIS 1.2 XML Actix-web json response create list Two-Dimensional Array

An array is an important construct in most programming languages. This post shows how to create one- and two-dimensional arrays in Rust. Although Rust has different ways of creating arrays, the following examples demonstrate some of them.

One-Dimensional Arrays

Before we move to two-dimensional Rust arrays, it is best to revisit one-dimensional arrays. Please check out How to Declare and Initialize an Array. As we already know, we always need to initialize arrays before we use them.  For example, the following codes will not compile.

To fix the compilation, we modify the codes as follows. These new codes will compile successfully.

Here is another example of a one-dimensional Rust array. Consider the following codes.

When we run these codes, we get the following output.

One-dimensional arrays are different from two-dimensional arrays. Below is a visual representation of a one-dimensional array. It has one set of indexes for its values, and setting or changing a value requires one index.

If we want to modify the index 0 (zero) value, we could change the above codes to the following.

When we run the new codes, we will get the following result.

Two-Dimensional Arrays

With one-dimensional arrays, we use one pair of square brackets. However, with two-dimensional arrays in Rust, we use multiple square brackets NOT placed side by side with each other. In Java, we would have something the following. Notice the pairs of square brackets sit side by side with each other Java

In Rust, we would have the following equivalent codes to declare and initialize a two-dimensional array. Strange, right? There are nested square brackets!

Therefore, the outer square brackets represent the rows, while the inner square brackets represent the columns of the two-dimensional Rust array. We can visualize the content of the variable my_int_matrix as follows. What if we need three- or n-dimensional arrays? Same drill. We use nested square brackets.

To display the contents of two-dimensional Rust array my_int_matrix :

Output:

We tested the codes using Rust 1.53.0, and this post is part of the Rust Programming Language For Beginners Tutorial.

Got comments, or suggestions? Please visit our Facebook page!

You Might Also Like