Learn about Tuples, one of Rust's compound data types.
Tuple is a Rust data type that is used to group multiple values.
It's defined using parantheses, for example:
// Here `(char, i32)` is variable's type, and `('A', 5)` is the value assigned to it
let chess_square: (char, i32) = ('A', 5);
Tuple is a Rust data type that is used to group multiple values.
It's defined using parantheses, for example:
// Here `(char, i32)` is variable's type, and `('A', 5)` is the value assigned to it
let chess_square: (char, i32) = ('A', 5);
Tuples have a fixed length. Their values must always contain the same number of elements as mentioned in the type signature:
let tuple_with_2_ints: (i32, i32) = (1, 2);
let tuple_with_3_ints: (i32, i32, i32) = (1, 2, 3);
// This is invalid because the value has < 3 elements
// let tuple_with_3_ints: (i32, i32, i32) = (1, 2);
// This is invalid too because the value has > 3 elements
// let tuple_with_3_ints: (i32, i32, i32) = (1, 2, 3, 4);
The elements in a tuple can be of different types, but they should be in the same order as mentioned in the type signature:
let tuple_with_int_and_char: (i32, char) = (1, 'A');
// This is a compile-time error because the value has 'char' as the first type, not 'i32'.
// let tuple_with_int_and_char: (i32, char) = ('A', 1);
In most cases, you don't need to annotate the type for a tuple. If a value is surrounded by parentheses and no type annotation is present, Rust infers the type based on the values used.
// Here the inferred type is (i32, char)
let tuple_with_int_and_char = (1, 'A');
The elements in a tuple can be accessed using two primary methods — indexing and destructuring.
Indexing is done by appending .<index>
to the variable name:
let chess_square = ('A', 5);
chess_square.0 // => Returns 'A'
chess_square.1 // => Returns '5'
Note that the indexes start from 0, not 1.
Attempting to access invalid indexes will raise a compile-time error:
let chess_square = ('A', 5);
chess_square.0 // => Returns 'A'
chess_square.1 // => Returns '5'
// This'll throw a compile-time error
// chess_square.2
Destructuring works by assigning multiple variables to the value at once:
let chess_square = ('A', 5);
let (column, row) = chess_square; // column is 'A', row is 5.
Destructuring requires that the number of variables on the left-hand side match the length of the tuple.
let chess_square = ('A', 5);
// This fails because the left-hand side only contains one value
// let (column) = chess_square;
// This fails because the left-hand side only contains >2 values
// let (column, row, index) = chess_square
// This works because the left-hand side contains exactly 2 values
let (column, row) = chess_square;
In this concept we covered Tuples, a Rust data type that is used to group multiple values.
(char, int32)
chess_square.0
, chess_square.1
let (row, column) = chess_square
You can read more about the tuple data type in the Data Types section of the Rust book.