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!();
  8. print!("Iterating over range:");
  9. for i in 0..3 {
  10. print!(" {}", array[i]);
  11. }
  12. println!();
  13. }

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)]
  3. fn transpose(matrix: [[i32; 3]; 3]) -> [[i32; 3]; 3] {
  4. unimplemented!()
  5. }
  6. fn pretty_print(matrix: &[[i32; 3]; 3]) {
  7. unimplemented!()
  8. }
  9. fn main() {
  10. let matrix = [
  11. [101, 102, 103], // <-- the comment makes rustfmt add a newline
  12. [201, 202, 203],
  13. [301, 302, 303],
  14. ];
  15. println!("matrix:");
  16. pretty_print(&matrix);
  17. let transposed = transpose(matrix);
  18. println!("transposed:");
  19. pretty_print(&transposed);
  20. }

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.