练习:嵌套数组

数组可以包含其他数组:

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)]

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

8. #[test]
9. fn test_transpose() {
10. let matrix = [
11. [101, 102, 103], //
12. [201, 202, 203],
13. [301, 302, 303],
14. ];
15. let transposed = transpose(matrix);
16. assert_eq!(
17. transposed,
18. [
19. [101, 201, 301], //
20. [102, 202, 302],
21. [103, 203, 303],
22. ]
23. );
24. }

26. fn main() {
27. let matrix = [
28. [101, 102, 103], // <-- the comment makes rustfmt add a newline
29. [201, 202, 203],
30. [301, 302, 303],
31. ];

33. println!("matrix: {:#?}", matrix);
34. let transposed = transpose(matrix);
35. println!("transposed: {:#?}", transposed);
36. }