There is no special 2D array type in Rust, but we can create an array of arrays, as arrays are values and can be copied. It is possible to loop over these arrays.
With for loops, we can iterate over each index of the arrays, but iter
and iter_mut
can be used for clearer code. Entire arrays can be replaced in a single statement.
This program creates an array of arrays (a 2D array) and then uses it in a variety of ways. It modifies elements and loops over the elements.
u32
.iter()
we can iterate safely over the elements of each array, and then also each nested array.for-range
loop. This loop will cause the clippy tool to recommend we use iter
instead.iter_mut
. Here we change all value 0 elements to have the value 1.fn main() { // Step 1: create an array of u32 arrays with all 0 initial values. // ... Then assign some elements. let mut data = [[0u32; 3]; 3]; data[0][0] = 100; data[0][1] = 150; data[2][2] = 200; println!("{:?}", data); // Step 2: replace the first array with a different array. data[0] = [8, 8, 8]; println!("{:?}", data); // Step 3: iterate over each row and column with nested for-loops and iter. for d in data.iter() { for c in d.iter() { print!("{}, ", c); } println!(); } // Step 4: iterate with for-range loops, and test for values greater than or equal to 100. for i in 0..data.len() { for x in 0..data[i].len() { if data[i][x] >= 100 { print!("***{}***, ", data[i][x]); } else { print!("{}, ", data[i][x]); } } println!(); } // Step 5: use iter_mut to change all elements equal to 0 to 1. for d in data.iter_mut() { for c in d.iter_mut() { if *c == 0 { *c = 1; } } } println!("{:?}", data); }[[100, 150, 0], [0, 0, 0], [0, 0, 200]] [[8, 8, 8], [0, 0, 0], [0, 0, 200]] 8, 8, 8, 0, 0, 0, 0, 0, 200, 8, 8, 8, 0, 0, 0, 0, 0, ***200***, [[8, 8, 8], [1, 1, 1], [1, 1, 200]]
By placing arrays within other arrays, we have a compact and efficient way to represent 2D arrays. We can address elements by accessing each array, one after another.