|
| 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; // pattern matching |
| 5 | + |
| 6 | + (boolean, integer) // return |
| 7 | +} |
| 8 | + |
| 9 | +#[derive(Debug)] |
| 10 | +struct Matrix(f32, f32, f32, f32); |
| 11 | + |
| 12 | +fn main() { |
| 13 | + // A tuple with a bunch of different types |
| 14 | + let long_tuple = (1u8, 2u16, 3u32, 4u64, |
| 15 | + -1i8, -2i16, -3i32, -4i64, |
| 16 | + 0.1f32, 0.2f64, |
| 17 | + 'a', true); |
| 18 | + |
| 19 | + // Values can be extracted from the tuple using tuple indexing |
| 20 | + println!("long tuple first value: {}", long_tuple.0); |
| 21 | + println!("long tuple second value: {}", long_tuple.1); |
| 22 | + |
| 23 | + // Tuples can be tuple members |
| 24 | + let tuple_of_tuples = ((1u8, 2u16, 2u32), (4u64, -1i8), -2i16); |
| 25 | + |
| 26 | + // Tuples are printable |
| 27 | + println!("tuple of tuples: {:?}", tuple_of_tuples); |
| 28 | + |
| 29 | + let pair = (1, true); |
| 30 | + println!("pair is {:?}", pair); |
| 31 | + |
| 32 | + println!("the reversed pair is {:?}", reverse(pair)); |
| 33 | + |
| 34 | + // To create one element tuples, the comma is required to tell them apart |
| 35 | + // from a literal surrounded by parentheses |
| 36 | + println!("one element tuple: {:?}", (5u32,)); |
| 37 | + println!("just an integer: {:?}", (5u32)); |
| 38 | + |
| 39 | + //tuples can be destructured to create bindings |
| 40 | + let tuple = (1, "hello", 4.5, true); |
| 41 | + |
| 42 | + let (a, b, c, d) = tuple; |
| 43 | + println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d); |
| 44 | + |
| 45 | + let matrix = Matrix(1.1, 1.2, 2.1, 2.2); |
| 46 | + println!("{:?}", matrix) |
| 47 | + |
| 48 | +} |
0 commit comments