Tuple and tuple indexing expressions
Tuple expressions
Syntax
TupleExpression →(TupleElements?)
TupleElements → (Expression, )+Expression?
Atuple expression constructstuple values.
The syntax for tuple expressions is a parenthesized, comma separated list of expressions, called thetuple initializer operands.
1-ary tuple expressions require a comma after their tuple initializer operand to be disambiguated with aparenthetical expression.
Tuple expressions are avalue expression that evaluate into a newly constructed value of a tuple type.
The number of tuple initializer operands is the arity of the constructed tuple.
Tuple expressions without any tuple initializer operands produce the unit tuple.
For other tuple expressions, the first written tuple initializer operand initializes the field0 and subsequent operands initializes the next highest field.For example, in the tuple expression('a', 'b', 'c'),'a' initializes the value of the field0,'b' field1, and'c' field2.
Examples of tuple expressions and their types:
| Expression | Type |
|---|---|
() | () (unit) |
(0.0, 4.5) | (f64, f64) |
("x".to_string(), ) | (String, ) |
("a", 4usize, true) | (&'static str, usize, bool) |
Tuple indexing expressions
Atuple indexing expression accesses fields oftuples andtuple structs.
The syntax for a tuple index expression is an expression, called thetuple operand, then a., then finally a tuple index.
The syntax for thetuple index is adecimal literal with no leading zeros, underscores, or suffix.For example0 and2 are valid tuple indices but not01,0_, nor0i32.
The type of the tuple operand must be atuple type or atuple struct.
The tuple index must be a name of a field of the type of the tuple operand.
Evaluation of tuple index expressions has no side effects beyond evaluation of its tuple operand.As aplace expression, it evaluates to the location of the field of the tuple operand with the same name as the tuple index.
Examples of tuple indexing expressions:
#![allow(unused)]fn main() {// Indexing a tuplelet pair = ("a string", 2);assert_eq!(pair.1, 2);// Indexing a tuple structstruct Point(f32, f32);let point = Point(1.0, 0.0);assert_eq!(point.0, 1.0);assert_eq!(point.1, 0.0);}
Note
Unlike field access expressions, tuple index expressions can be the function operand of acall expression as it cannot be confused with a method call since method names cannot be numbers.
Note
Although arrays and slices also have elements, you must use anarray or slice indexing expression or aslice pattern to access their elements.