]>
Commit | Line | Data |
---|---|---|
13cf67c4 XL |
1 | # Tuple types |
2 | ||
3 | > **<sup>Syntax</sup>**\ | |
4 | > _TupleType_ :\ | |
5 | > `(` `)`\ | |
6 | > | `(` ( [_Type_] `,` )<sup>+</sup> [_Type_]<sup>?</sup> `)` | |
7 | ||
29967ef6 XL |
8 | The *tuple type* is a structural type[^1] for heterogeneous lists of other |
9 | types. Each entry in the list is an *element*[^2] of the tuple. The position of | |
10 | the element makes it the *nth element* using zero (`0`) as the initial index. | |
13cf67c4 | 11 | |
29967ef6 XL |
12 | The number of elements determines the arity of the tuple. A tuple with `n` |
13 | elements is called an `n-ary tuple`. For example, a tuple with 2 elements is a | |
14 | 2-ary tuple. | |
13cf67c4 | 15 | |
29967ef6 XL |
16 | For convenience and historical reasons, the tuple type with no elements (`()`) |
17 | is often called *unit* or *the unit type*. It's one value is also called *unit* | |
18 | or *the unit value*. | |
13cf67c4 | 19 | |
29967ef6 XL |
20 | Tuple types are written by listing the types of their elements in a |
21 | parenthesized, comma-separated list. 1-ary tuples require a comma after their | |
22 | element type to be disambiguated with a [parenthesized type]. | |
13cf67c4 | 23 | |
29967ef6 | 24 | Some examples of tuple types: |
13cf67c4 | 25 | |
29967ef6 XL |
26 | * `()` (unit) |
27 | * `(f64, f64)` | |
28 | * `(String, i32)` | |
29 | * `(i32, String)` (different type from the previous example) | |
30 | * `(i32, f64, Vec<String>, Option<bool>)` | |
13cf67c4 | 31 | |
29967ef6 XL |
32 | Values of this type are constructed using a [tuple expression]. Furthermore, |
33 | various expressions will produce the unit value if there is no other meaningful | |
34 | value for it to evaluate to. Tuple elements can be accessed by either a [tuple | |
35 | index expression] or [pattern matching]. | |
36 | ||
37 | [^1]: Structural types are always equivalent if their internal types are | |
38 | equivalent. For a nominal version of tuples, see [tuple structs]. | |
39 | [^2]: Element is equivalent to field, except numerical indexes instead of | |
40 | identifiers | |
13cf67c4 | 41 | |
416331ca | 42 | [_Type_]: ../types.md#type-expressions |
29967ef6 XL |
43 | [parenthesized type]: ../types.md#parenthesized-types |
44 | [pattern matching]: ../patterns.md#tuple-patterns | |
45 | [tuple expression]: ../expressions/tuple-expr.md#tuple-expressions | |
46 | [tuple index expression]: ../expressions/tuple-expr.md#tuple-indexing-expressions | |
47 | [tuple structs]: ./struct.md |