On this page
article
Tuples
What are Tuples?
- Tuples are heterogeneous sequences of elements, meaning, each element in a tuple can have a different data type. Just like arrays, tuples are of a fixed length.
- Define a Tuple
A tuple can be defined by writing let followed by the name of the tuple and then enclosing the values within the parenthesis.
- Syntax 1
- The syntax below defines a tuple without specifying the type. However, the compiler can infer the type.
- Syntax 2
- The syntax below defines a tuple by specifying the type.
Example
The following illustration explains the concept:
- Access the Value of the Tuple
- Unlike array which uses
[]
for accessing an element, the value of the tuple can be accessed using the dot operator(.)
.
To get the individual values out of a tuple, we can use pattern matching to destructure a tuple value, like this:
output:-
How to Make a Tuple Mutable?
Just like a variable becomes mutable by adding the mut keyword after let, the same goes for a tuple.
output:-
Print the Tuple
The whole tuple can be traversed using the debug trait.
output:-
Quiz
Test your understanding of tuples in Rust!
Last updated a year ago.