|
1 |
| -// function that returns two values |
2 |
| -fn chimpanzees() -> (int, &str) { |
3 |
| - (6, "Pan troglodytes") |
4 |
| -} |
5 |
| - |
6 |
| -fn elephants() -> (int, &str) { |
7 |
| - (9, "Elephas maximus") |
8 |
| -} |
| 1 | +// tuples can be used as function arguments and as return values |
| 2 | +fn reverse(pair: (int, bool)) -> (bool, int) { |
| 3 | + // `let` can be used to bind the members of a tuple to variables |
| 4 | + let (integer, boolean) = pair; |
9 | 5 |
|
10 |
| -fn penguins() -> (int, &str) { |
11 |
| - (4, "Spheniscus demersus") |
12 |
| -} |
13 |
| - |
14 |
| -fn wolves() -> (int, &str) { |
15 |
| - (6, "Canis lupus") |
16 |
| -} |
17 |
| - |
18 |
| -// tuples can be function arguments |
19 |
| -fn show(pair: (int, &str)) { |
20 |
| - // destructuring a tuple |
21 |
| - let (amount, species) = pair; |
22 |
| - |
23 |
| - println!("There are {} {}", amount, species); |
| 6 | + (boolean, integer) |
24 | 7 | }
|
25 | 8 |
|
26 | 9 | fn main() {
|
27 | 10 | // a tuple with a bunch of different types
|
28 | 11 | let long_tuple = (1u8, 2u16, 3u32, 4u64,
|
29 | 12 | -1i8, -2i16, -3i32, -4i64,
|
30 | 13 | 0.1f32, 0.2f64,
|
31 |
| - 'a', "abc"); |
| 14 | + 'a', true); |
32 | 15 |
|
33 | 16 | // values can be extracted from the tuple using the valN methods
|
34 | 17 | println!("long tuple first value: {}", long_tuple.val0());
|
35 | 18 | println!("long tuple second value: {}", long_tuple.val1());
|
36 | 19 |
|
37 |
| - // `let` can be used to bind a tuple members to variables |
38 |
| - let pair = (3, 4); |
39 |
| - let (x, y) = pair; |
40 |
| - println!("x is {}, and y is {}", x, y); |
| 20 | + // tuples can be tuple members |
| 21 | + let tuple_of_tuples = ((1u8, 2u16, 2u32), (4u64, -1i8), -2i16); |
41 | 22 |
|
42 |
| - // but you can also print a tuple directly |
| 23 | + // tuples are printable |
| 24 | + let pair = (1, true); |
43 | 25 | println!("pair is {}", pair);
|
44 | 26 |
|
45 |
| - // a tuple of tuples |
46 |
| - let tuple_of_tuples = ((1u8, 2u16, 2u32), (4u64, -1i8), -2i16); |
47 |
| - |
48 |
| - println!("Animal inventory"); |
49 |
| - show(chimpanzees()); |
50 |
| - show(elephants()); |
51 |
| - show(penguins()); |
52 |
| - show(wolves()); |
| 27 | + println!("the reversed pair is {}", reverse(pair)); |
53 | 28 | }
|
0 commit comments