3 A tuple is a collection of values of different types. Tuples are constructed
4 using parentheses `()`, and each tuple itself is a value with type signature
5 `(T1, T2, ...)`, where `T1`, `T2` are the types of its members. Functions can
6 use tuples to return multiple values, as tuples can hold any number of values.
9 // Tuples can be used as function arguments and as return values
10 fn reverse(pair: (i32, bool)) -> (bool, i32) {
11 // `let` can be used to bind the members of a tuple to variables
12 let (integer, boolean) = pair;
17 // The following struct is for the activity.
19 struct Matrix(f32, f32, f32, f32);
22 // A tuple with a bunch of different types
23 let long_tuple = (1u8, 2u16, 3u32, 4u64,
24 -1i8, -2i16, -3i32, -4i64,
28 // Values can be extracted from the tuple using tuple indexing
29 println!("long tuple first value: {}", long_tuple.0);
30 println!("long tuple second value: {}", long_tuple.1);
32 // Tuples can be tuple members
33 let tuple_of_tuples = ((1u8, 2u16, 2u32), (4u64, -1i8), -2i16);
35 // Tuples are printable
36 println!("tuple of tuples: {:?}", tuple_of_tuples);
38 // But long Tuples (more than 12 elements) cannot be printed
39 // let too_long_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
40 // println!("too long tuple: {:?}", too_long_tuple);
41 // TODO ^ Uncomment the above 2 lines to see the compiler error
44 println!("pair is {:?}", pair);
46 println!("the reversed pair is {:?}", reverse(pair));
48 // To create one element tuples, the comma is required to tell them apart
49 // from a literal surrounded by parentheses
50 println!("one element tuple: {:?}", (5u32,));
51 println!("just an integer: {:?}", (5u32));
53 //tuples can be destructured to create bindings
54 let tuple = (1, "hello", 4.5, true);
56 let (a, b, c, d) = tuple;
57 println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d);
59 let matrix = Matrix(1.1, 1.2, 2.1, 2.2);
60 println!("{:?}", matrix);
67 1. *Recap*: Add the `fmt::Display` trait to the `Matrix` struct in the above example,
68 so that if you switch from printing the debug format `{:?}` to the display
69 format `{}`, you see the following output:
76 You may want to refer back to the example for [print display][print_display].
77 2. Add a `transpose` function using the `reverse` function as a template, which
78 accepts a matrix as an argument, and returns a matrix in which two elements
79 have been swapped. For example:
82 println!("Matrix:\n{}", matrix);
83 println!("Transpose:\n{}", transpose(matrix));
86 results in the output:
97 [print_display]: ../hello/print/print_display.md