To create a two-dimensional vector in Rust, you can use a vector of vectors.
In this example,
matrix
as a vector of vectors, where each inner vector represents a row of the two-dimensional vector.matrix
with numeric vectors using the vec!
macro.fn main() {
// Step 1: Create a numeric two-dimensional vector
let matrix: Vec<Vec<i32>> = vec![
vec![1, 2, 3],
vec![4, 5, 6],
vec![7, 8, 9]
];
// Step 2: Print the two-dimensional vector
println!("{:?}", matrix);
}
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In this example,
matrix
as a vector of vectors, where each inner vector represents a row of the two-dimensional vector.matrix
with string vectors using the vec!
macro.fn main() {
// Step 1: Create a string two-dimensional vector
let matrix: Vec<Vec<&str>> = vec![
vec!["a", "b", "c"],
vec!["d", "e", "f"],
vec!["g", "h", "i"]
];
// Step 2: Print the two-dimensional vector
println!("{:?}", matrix);
}
[["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]
In this tutorial, we learned How to create a Two Dimensional Vector in Rust language with well detailed examples.