]>
Commit | Line | Data |
---|---|---|
ea8adc8c XL |
1 | # Tuple and tuple indexing expressions |
2 | ||
3 | ## Tuple expressions | |
4 | ||
8faf50e0 XL |
5 | > **<sup>Syntax</sup>**\ |
6 | > _TupleExpression_ :\ | |
13cf67c4 XL |
7 | > `(` [_InnerAttribute_]<sup>\*</sup> _TupleElements_<sup>?</sup> `)` |
8 | > | |
9 | > _TupleElements_ :\ | |
10 | > ( [_Expression_] `,` )<sup>+</sup> [_Expression_]<sup>?</sup> | |
0531ce1d | 11 | |
ea8adc8c | 12 | Tuples are written by enclosing zero or more comma-separated expressions in |
416331ca | 13 | parentheses. They are used to create [tuple-typed](../types/tuple.md) |
ea8adc8c XL |
14 | values. |
15 | ||
16 | ```rust | |
17 | (0.0, 4.5); | |
18 | ("a", 4usize, true); | |
19 | (); | |
20 | ``` | |
21 | ||
22 | You can disambiguate a single-element tuple from a value in parentheses with a | |
23 | comma: | |
24 | ||
25 | ```rust | |
26 | (0,); // single-element tuple | |
27 | (0); // zero in parentheses | |
28 | ``` | |
29 | ||
13cf67c4 XL |
30 | ### Tuple expression attributes |
31 | ||
32 | [Inner attributes] are allowed directly after the opening parenthesis of a | |
33 | tuple expression in the same expression contexts as [attributes on block | |
34 | expressions]. | |
35 | ||
ea8adc8c XL |
36 | ## Tuple indexing expressions |
37 | ||
8faf50e0 XL |
38 | > **<sup>Syntax</sup>**\ |
39 | > _TupleIndexingExpression_ :\ | |
0531ce1d XL |
40 | > [_Expression_] `.` [TUPLE_INDEX] |
41 | ||
416331ca | 42 | [Tuples](../types/tuple.md) and [struct tuples](../items/structs.md) can be |
ea8adc8c | 43 | indexed using the number corresponding to the position of the field. The index |
416331ca | 44 | must be written as a [decimal literal](../tokens.md#integer-literals) with no |
ea8adc8c XL |
45 | underscores or suffix. Tuple indexing expressions also differ from field |
46 | expressions in that they can unambiguously be called as a function. In all | |
47 | other aspects they have the same behavior. | |
48 | ||
49 | ```rust | |
50 | # struct Point(f32, f32); | |
51 | let pair = (1, 2); | |
52 | assert_eq!(pair.1, 2); | |
53 | let unit_x = Point(1.0, 0.0); | |
54 | assert_eq!(unit_x.0, 1.0); | |
55 | ``` | |
0531ce1d | 56 | |
416331ca XL |
57 | [Inner attributes]: ../attributes.md |
58 | [TUPLE_INDEX]: ../tokens.md#integer-literals | |
59 | [_Expression_]: ../expressions.md | |
60 | [_InnerAttribute_]: ../attributes.md | |
61 | [attributes on block expressions]: block-expr.md#attributes-on-block-expressions |