Tuple

  1. 🌟 Elements in a tuple can have different types. Tuple’s type signature is (T1, T2, ...), where T1, T2 are the types of tuple’s members.
2. fn main() {
3. let _t0: (u8,i16) = (0, -1);
4. // Tuples can be tuple's members
5. let _t1: (u8, (i16, u32)) = (0, (-1, 1));
6. // Fill the blanks to make the code work
7. let t: (u8, __, i64, __, __) = (1u8, 2u16, 3i64, "hello", String::from(", world"));

9. println!("Success!");
10. }
  1. 🌟 Members can be extracted from the tuple using indexing.
2. // Make it work
3. fn main() {
4. let t = ("i", "am", "sunface");
5. assert_eq!(t.1, "sunface");

7. println!("Success!");
8. }
  1. 🌟 Long tuples cannot be printed
2. // Fix the error
3. fn main() {
4. let too_long_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
5. println!("too long tuple: {:?}", too_long_tuple);
6. }
  1. 🌟 Destructuring tuple with pattern.
2. fn main() {
3. let tup = (1, 6.4, "hello");

5. // Fill the blank to make the code work
6. let __ = tup;

8. assert_eq!(x, 1);
9. assert_eq!(y, "hello");
10. assert_eq!(z, 6.4);

12. println!("Success!");
13. }
  1. 🌟🌟 Destructure assignments.
1. fn main() {
2. let (x, y, z);

4. // Fill the blank
5. __ = (1, 2, 3);

7. assert_eq!(x, 3);
8. assert_eq!(y, 1);
9. assert_eq!(z, 2);

11. println!("Success!");
12. }
  1. 🌟🌟 Tuples can be used as function arguments and return values
2. fn main() {
3. // Fill the blank, need a few computations here.
4. let (x, y) = sum_multiply(__);

6. assert_eq!(x, 5);
7. assert_eq!(y, 6);

9. println!("Success!");
10. }

12. fn sum_multiply(nums: (i32, i32)) -> (i32, i32) {
13. (nums.0 + nums.1, nums.0 * nums.1)
14. }

You can find the solutions here(under the solutions path), but only use it when you need it