Rust Tuples
A tuple groups several values of possibly different types into one. It’s a quick way to bundle related things together without defining a whole new type for them.
Creating a tuple
Section titled “Creating a tuple”fn main() { let person: (&str, i32, bool) = ("Alice", 30, true); println!("{:?}", person);}Output:
("Alice", 30, true)Notice the tuple mixes a &str, an i32, and a bool in one value — something an array can’t do, since every element in an array must be the same type.
Accessing elements by position
Section titled “Accessing elements by position”Use .0, .1, .2, and so on — tuples are indexed starting at zero:
fn main() { let person = ("Alice", 30, true);
println!("Name: {}", person.0); println!("Age: {}", person.1); println!("Active: {}", person.2);}Destructuring a tuple
Section titled “Destructuring a tuple”You can pull every value out into its own variable in one line:
fn main() { let person = ("Alice", 30, true); let (name, age, is_active) = person;
println!("{name} is {age}, active: {is_active}");}This is often clearer than repeated .0, .1, .2 access, especially once a tuple has more than two or three fields.
Returning multiple values from a function
Section titled “Returning multiple values from a function”Tuples are the natural way to return more than one value, since a function can only declare one return type:
fn min_max(numbers: &[i32]) -> (i32, i32) { let min = *numbers.iter().min().unwrap(); let max = *numbers.iter().max().unwrap(); (min, max)}
fn main() { let (smallest, largest) = min_max(&[4, 8, 1, 9, 3]); println!("min: {smallest}, max: {largest}");}The empty tuple: ()
Section titled “The empty tuple: ()”You’ve actually already met a tuple without realizing it. () is called the unit type, and it’s what a function returns when it doesn’t return anything meaningful — it’s the implicit return type of fn main().
When to use a tuple vs a struct
Section titled “When to use a tuple vs a struct”Tuples are great for quick, unnamed groupings — especially returning two or three values from a function. Once a group of values represents a real concept with named fields (like a Person with a name and age you’ll refer to by name throughout your code), a struct is usually the better, more readable choice.
- A tuple groups values of possibly different types:
(name, age, is_active). - Access fields with
.0,.1,.2, or pull them all out at once with destructuring. - Tuples are a natural way to return multiple values from a function.
- For named, reusable groupings, reach for a struct instead.
Quick check
Section titled “Quick check”Quick check
1. What can a tuple hold that an array cannot?
2. How do you access the second element of a tuple called person?
Score: 0 / 2