Arrays and for Loops

We saw that an array can be declared like this:

1. #![allow(unused)]
2. fn main() {
3. let array = [10, 20, 30];
4. }

You can print such an array by asking for its debug representation with {:?}:

1. fn main() {
2. let array = [10, 20, 30];
3. println!("array: {array:?}");
4. }

Rust lets you iterate over things like arrays and ranges using the for keyword:

1. fn main() {
2. let array = [10, 20, 30];
3. print!("Iterating over array:");
4. for n in array {
5. print!(" {n}");
6. }
7. println!();

9. print!("Iterating over range:");
10. for i in 0..3 {
11. print!(" {}", array[i]);
12. }
13. println!();
14. }

Use the above to write a function pretty_print which pretty-print a matrix and a function transpose which will transpose a matrix (turn rows into columns):

7.2. Arrays and for Loops - 图1

Hard-code both functions to operate on 3 × 3 matrices.

Copy the code below to <https://play.rust-lang.org/> and implement the functions:

1. // TODO: remove this when you're done with your implementation.
2. #![allow(unused_variables, dead_code)]

4. fn transpose(matrix: [[i32; 3]; 3]) -> [[i32; 3]; 3] {
5. unimplemented!()
6. }

8. fn pretty_print(matrix: &[[i32; 3]; 3]) {
9. unimplemented!()
10. }

12. fn main() {
13. let matrix = [
14. [101, 102, 103], // <-- the comment makes rustfmt add a newline
15. [201, 202, 203],
16. [301, 302, 303],
17. ];

19. println!("matrix:");
20. pretty_print(&matrix);

22. let transposed = transpose(matrix);
23. println!("transposed:");
24. pretty_print(&transposed);
25. }

Bonus Question

Could you use &[i32] slices instead of hard-coded 3 × 3 matrices for your argument and return types? Something like &[&[i32]] for a two-dimensional slice-of-slices. Why or why not?

See the ndarray crate for a production quality implementation.

The solution and the answer to the bonus section are available in the Solution section.