练习:嵌套数组

数组可以包含其他数组:

  1. #![allow(unused)]
  2. fn main() {
  3. let array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
  4. }

What is the type of this variable?

Use an array such as the above to write a function transpose which will transpose a matrix (turn rows into columns):

8.5. 练习:嵌套数组 - 图1

硬编码这两个函数,让它们处理 3 × 3 的矩阵。

将下面的代码复制到 https://play.rust-lang.org/ 并实现上述函数:

  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. #[test]
  7. fn test_transpose() {
  8. let matrix = [
  9. [101, 102, 103], //
  10. [201, 202, 203],
  11. [301, 302, 303],
  12. ];
  13. let transposed = transpose(matrix);
  14. assert_eq!(
  15. transposed,
  16. [
  17. [101, 201, 301], //
  18. [102, 202, 302],
  19. [103, 203, 303],
  20. ]
  21. );
  22. }
  23. fn main() {
  24. let matrix = [
  25. [101, 102, 103], // <-- the comment makes rustfmt add a newline
  26. [201, 202, 203],
  27. [301, 302, 303],
  28. ];
  29. println!("matrix: {:#?}", matrix);
  30. let transposed = transpose(matrix);
  31. println!("transposed: {:#?}", transposed);
  32. }