Rust has a different construct for creating arrays.
One-Dimensional Arrays
Before we move to two-dimensional arrays, it is best to revisit one-dimensional arrays. Please check out How to Declare and Initialize an Array.
Sample Codes
Consider the following codes.
1 2 3 4 5 |
let my_keywords:[&str; 2] = ["EMPTY"; 2]; for my_keyword in my_keywords.iter() { println!("{}", my_keyword); } |
Output:
1 2 |
EMPTY EMPTY |
Our array looks like this visually.
Two-Dimensional Arrays
When creating two-dimensional arrays, we still use multiple square brackets but not placed side by side with each other.
In Java, we would have something like this:
1 2 3 4 5 6 7 8 |
int[][] myIntMatrix = new int[3][2]; for(int i = 0; i < 3; i++ ) { for(int j = 0; j < 2; j++ ) { myIntMatrix[i][j] = 8; } } |
In Rust, we would have:
1 |
let my_int_matrix:[[i32;2];3] = [[8;2];3]; |
my_int_matrix is visually represented as:
Therefore, the outer square bracket represents the rows and the inner square bracket represents the columns.
To display the contents of my_int_matrix :
1 2 3 4 5 |
for (i, row) in my_int_matrix.iter().enumerate() { for (j, col) in row.iter().enumerate() { println!("[row={}][col={}]={}", i, j, col); } } |
Output:
1 2 3 4 5 6 |
[row=0][col=0]=8 [row=0][col=1]=8 [row=1][col=0]=8 [row=1][col=1]=8 [row=2][col=0]=8 [row=2][col=1]=8 |
This post is part of the Rust Programming Language For Beginners Tutorial.