2D Array ExamplesCreate a 2D array by initializing an array of arrays, and assign elements. Loop over the arrays and modify them.
Rust
2D array. 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.
Example. 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.
Step 1 We create an array of 3, 3-element arrays, all initialized with the 0 value and with the type of u32.
Step 2 We can assign an array to a different array, and we change the first row to have all value 8 elements.
Step 3 With iter() we can iterate safely over the elements of each array, and then also each nested array.
iter
Step 4 If we need to have indexes available, we can use a for-range loop. This loop will cause the clippy tool to recommend we use iter instead.
for
Step 5 We can modify arrays in a loop by using 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]]
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.