Tuples
A tuple is a collection of values of different types. Tuples are constructed
using parentheses (), and each tuple itself is a value with type signature
(T1, T2, ...), where T1, T2 are the types of its members. Functions can
use tuples to return multiple values, as tuples can hold any number of values.
1. // Tuples can be used as function arguments and as return values
2. fn reverse(pair: (i32, bool)) -> (bool, i32) {
3. // `let` can be used to bind the members of a tuple to variables
4. let (integer, boolean) = pair;
6. (boolean, integer)
7. }
9. // The following struct is for the activity.
10. #[derive(Debug)]
11. struct Matrix(f32, f32, f32, f32);
13. fn main() {
14. // A tuple with a bunch of different types
15. let long_tuple = (1u8, 2u16, 3u32, 4u64,
16. -1i8, -2i16, -3i32, -4i64,
17. 0.1f32, 0.2f64,
18. 'a', true);
20. // Values can be extracted from the tuple using tuple indexing
21. println!("long tuple first value: {}", long_tuple.0);
22. println!("long tuple second value: {}", long_tuple.1);
24. // Tuples can be tuple members
25. let tuple_of_tuples = ((1u8, 2u16, 2u32), (4u64, -1i8), -2i16);
27. // Tuples are printable
28. println!("tuple of tuples: {:?}", tuple_of_tuples);
30. // But long Tuples cannot be printed
31. // let too_long_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
32. // println!("too long tuple: {:?}", too_long_tuple);
33. // TODO ^ Uncomment the above 2 lines to see the compiler error
35. let pair = (1, true);
36. println!("pair is {:?}", pair);
38. println!("the reversed pair is {:?}", reverse(pair));
40. // To create one element tuples, the comma is required to tell them apart
41. // from a literal surrounded by parentheses
42. println!("one element tuple: {:?}", (5u32,));
43. println!("just an integer: {:?}", (5u32));
45. //tuples can be destructured to create bindings
46. let tuple = (1, "hello", 4.5, true);
48. let (a, b, c, d) = tuple;
49. println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d);
51. let matrix = Matrix(1.1, 1.2, 2.1, 2.2);
52. println!("{:?}", matrix);
54. }
Activity
- Recap: Add the
fmt::Displaytrait to the Matrixstructin the above example, so that if you switch from printing the debug format{:?}to the display format{}, you see the following output:
1. ( 1.1 1.2 )
2. ( 2.1 2.2 )
You may want to refer back to the example for print display.
2. Add a transpose function using the reverse function as a template, which
accepts a matrix as an argument, and returns a matrix in which two elements
have been swapped. For example:
1. println!("Matrix:\n{}", matrix);
2. println!("Transpose:\n{}", transpose(matrix));
results in the output:
1. Matrix:
2. ( 1.1 1.2 )
3. ( 2.1 2.2 )
4. Transpose:
5. ( 1.1 2.1 )
6. ( 1.2 2.2 )
