Skip to content

Commit 28aa4ee

Browse files
author
Jorge Aparicio
committed
tuples: don't use unexplained concepts. Closes #45
1 parent 8116beb commit 28aa4ee

File tree

2 files changed

+15
-39
lines changed

2 files changed

+15
-39
lines changed

src/tuples/input.md

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
A tuple is a collection of values of different types. Tuples are declared
2-
using parentheses `()`, and each tuple belongs to a type of the form
3-
`(T1, T2, ...)`. Function can use tuples to return multiple values.
1+
A tuple is a collection of values of different types. Tuples are constructed
2+
using parentheses `()`, and each tuple itself is a value with type signature
3+
`(T1, T2, ...)`, where `T1`, `T2` are the types of its members. Functions can
4+
use tuples to return multiple values, as tuples can hold any number of values.
45

56
{tuples.rs}
67

src/tuples/tuples.rs

Lines changed: 11 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,28 @@
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;
95

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)
247
}
258

269
fn main() {
2710
// a tuple with a bunch of different types
2811
let long_tuple = (1u8, 2u16, 3u32, 4u64,
2912
-1i8, -2i16, -3i32, -4i64,
3013
0.1f32, 0.2f64,
31-
'a', "abc");
14+
'a', true);
3215

3316
// values can be extracted from the tuple using the valN methods
3417
println!("long tuple first value: {}", long_tuple.val0());
3518
println!("long tuple second value: {}", long_tuple.val1());
3619

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);
4122

42-
// but you can also print a tuple directly
23+
// tuples are printable
24+
let pair = (1, true);
4325
println!("pair is {}", pair);
4426

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));
5328
}

0 commit comments

Comments
 (0)