In this lesson, you will learn how to group multiple related values into a single variable using tuples and arrays.
Tuples: Heterogeneous Groups
A tuple is a way to group together a fixed number of elements that can have different data types. Think of it as a small, fixed-size "package" for related data. You define a tuple by putting values inside parentheses, separated by commas.
// A tuple containing an integer, a float, and a boolean
let user_data = (1, 3.14, true);
You can access elements in a tuple using "tuple indexing" (the period followed by the index starting at zero):
let id = user_data.0;
let score = user_data.1;
Tuples are perfect for returning multiple values from a function or grouping a small, temporary set of related variables.
Arrays: Homogeneous Collections
An array is a collection of values where every element must have the same type. Unlike tuples, arrays are very useful when you want to store a list of items that are all of the same nature, such as a sequence of numbers.
You define an array using square brackets. Because arrays have a fixed size that is part of their type signature, you must specify the size if you want to be explicit, though Rust can often infer it:
// An array of 5 integers
let scores: [i32; 5] = [10, 20, 30, 40, 50];
// Accessing the first element
let first = scores[0];
The key difference here is memory: both tuples and arrays are allocated on the stack, providing fast access. While a tuple is a "bag" of mixed types, an array is a "list" of identical types. Choosing between them depends on whether your data belongs together logically regardless of type (tuple) or if you are handling a consistent sequence of the same data type (array).
Key Takeaway: Tuples let you group different types together, while arrays are for fixed-size lists of a single type; both are stack-allocated and provide a way to manage related data points as one unit.