]> git.proxmox.com Git - rustc.git/blame - src/doc/reference/src/expressions/tuple-expr.md
New upstream version 1.38.0+dfsg1
[rustc.git] / src / doc / reference / src / expressions / tuple-expr.md
CommitLineData
ea8adc8c
XL
1# Tuple and tuple indexing expressions
2
3## Tuple expressions
4
8faf50e0
XL
5> **<sup>Syntax</sup>**\
6> _TupleExpression_ :\
13cf67c4
XL
7> &nbsp;&nbsp; `(` [_InnerAttribute_]<sup>\*</sup> _TupleElements_<sup>?</sup> `)`
8>
9> _TupleElements_ :\
10> &nbsp;&nbsp; ( [_Expression_] `,` )<sup>+</sup> [_Expression_]<sup>?</sup>
0531ce1d 11
ea8adc8c 12Tuples are written by enclosing zero or more comma-separated expressions in
416331ca 13parentheses. They are used to create [tuple-typed](../types/tuple.md)
ea8adc8c
XL
14values.
15
16```rust
17(0.0, 4.5);
18("a", 4usize, true);
19();
20```
21
22You can disambiguate a single-element tuple from a value in parentheses with a
23comma:
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
33tuple expression in the same expression contexts as [attributes on block
34expressions].
35
ea8adc8c
XL
36## Tuple indexing expressions
37
8faf50e0
XL
38> **<sup>Syntax</sup>**\
39> _TupleIndexingExpression_ :\
0531ce1d
XL
40> &nbsp;&nbsp; [_Expression_] `.` [TUPLE_INDEX]
41
416331ca 42[Tuples](../types/tuple.md) and [struct tuples](../items/structs.md) can be
ea8adc8c 43indexed using the number corresponding to the position of the field. The index
416331ca 44must be written as a [decimal literal](../tokens.md#integer-literals) with no
ea8adc8c
XL
45underscores or suffix. Tuple indexing expressions also differ from field
46expressions in that they can unambiguously be called as a function. In all
47other aspects they have the same behavior.
48
49```rust
50# struct Point(f32, f32);
51let pair = (1, 2);
52assert_eq!(pair.1, 2);
53let unit_x = Point(1.0, 0.0);
54assert_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