Skip to content

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.

fn main() {
let person: (&str, i32, bool) = ("Alice", 30, true);
println!("{:?}", person);
}

Output:

("Alice", 30, true)
▶ Try it Yourself

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.

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);
}
▶ Try it Yourself

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}");
}
▶ Try it Yourself

This is often clearer than repeated .0, .1, .2 access, especially once a tuple has more than two or three fields.

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}");
}
▶ Try it Yourself

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().

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

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