To create a Two Dimensional Array in Rust, you can use an array of arrays or a vector of arrays.
In this example,
matrix
with dimensions 3x3.fn main() {
let mut matrix = [[0; 3]; 3];
for i in 0..3 {
for j in 0..3 {
matrix[i][j] = i + j;
}
}
println!("{:?}", matrix);
}
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
In this example,
std::vec::Vec
.matrix
with dimensions 2x2.fn main() {
let mut matrix: Vec<[char; 2]> = Vec::new();
for i in 0..2 {
let mut row = ['A'; 2];
for j in 0..2 {
row[j] = (b'A' + (i + j) as u8) as char;
}
matrix.push(row);
}
println!("{:?}", matrix);
}
[["A", "B"], ["B", "C"]]
In this tutorial, we learned How to create a Two Dimensional Array in Rust language with well detailed examples.