Reputation: 338
I wish like define and assign a 2D array in a single line in Rust. That is, replace this excessive code with a single line, by example:
fn main() {
println!("Sample of array 2D");
let N = 4;
let mut a = vec![vec![0; N]; N];
// row 0
a[0][0] = 00;
a[0][1] = 10;
a[0][2] = 35;
a[0][3] = 30;
// row 0
a[1][0] = 10;
a[1][1] = 00;
a[1][2] = 30;
a[1][3] = 15;
// row 0
a[2][0] = 35;
a[2][1] = 30;
a[2][2] = 05;
a[2][3] = 30;
// row 0
a[3][0] = 30;
a[3][1] = 15;
a[3][2] = 30;
a[3][3] = 00;
println!("MATRIX\n{:?}", a);
}
Say, something equivalent to how I do it in C#:
int[,] a = {
{ 00, 10, 35, 30 },
{ 10, 00, 30, 15 },
{ 35, 30, 00, 30 },
{ 30, 15, 30, 00 }
};
P.S. Excuse me if the question is too simple, I am learning Rust
Upvotes: 1
Views: 255
Reputation: 42678
Just use nested vecs:
fn main() {
println!("Sample of array 2D");
let a: Vec<Vec<usize>> = vec![
vec![00, 10, 35, 30], vec![10, 00, 30, 15], ...
];
println!("MATRIX\n{:?}", a);
}
Or arrays:
let a: [[usize; 4];4] = [
[00, 10, 35, 30],
[10, 00, 30, 15],
[00, 10, 35, 30],
[10, 00, 30, 15]
];
Upvotes: 2