Rust Tuples
A tuple bundles a fixed number of values together into one compound value. Unlike arrays, the values in a tuple can have different types. Tuples are perfect for small, short-lived groupings — such as returning two results from a function — where defining a full struct would be overkill.
Creating a tuple
Write the values in parentheses, separated by commas. The type of a tuple lists the type of each position.
fn main() {
let person: (&str, u32, bool) = ("Mira", 34, true);
let rgb = (255, 128, 0);
println!("{:?}", person);
println!("{:?}", rgb);
}("Mira", 34, true)
(255, 128, 0)
The length and types are fixed: person will always hold exactly a string slice, a u32 and a bool, in that order.
Accessing elements by position
Use a dot followed by the index, starting from 0. Note that this is t.0, not t[0] — tuples are not indexed with square brackets.
fn main() {
let mut book = ("Dune", 1965, 4.6);
println!("Title: {}", book.0);
println!("Year: {}", book.1);
println!("Rating: {}", book.2);
book.2 = 4.8; // tuples declared with mut can be changed
println!("New rating: {}", book.2);
}Title: Dune
Year: 1965
Rating: 4.6
New rating: 4.8
You can change an element's value, but never its type: book.1 = "old" would not compile, because position 1 is an integer.
Destructuring
Instead of writing .0, .1, .2 everywhere, you can destructure a tuple — unpack it into separate variables in one let. Use _ for parts you don't need.
fn main() {
let city = ("Lisbon", 545_000, "Portugal");
let (name, population, country) = city;
println!("{} in {} has {} people", name, country, population);
let (only_name, _, _) = city;
println!("Just the name: {}", only_name);
}Lisbon in Portugal has 545000 people
Just the name: Lisbon
Returning multiple values
Functions in Rust return a single value, but that value can be a tuple. This is the most common reason to use tuples.
fn min_max(values: &[i32]) -> (i32, i32) {
let mut lo = values[0];
let mut hi = values[0];
for &v in values {
if v < lo { lo = v; }
if v > hi { hi = v; }
}
(lo, hi)
}
fn divide(a: u32, b: u32) -> (u32, u32) {
(a / b, a % b)
}
fn main() {
let (low, high) = min_max(&[7, -3, 12, 5]);
println!("Lowest: {}, highest: {}", low, high);
let (q, r) = divide(17, 5);
println!("17 / 5 = {} remainder {}", q, r);
}Lowest: -3, highest: 12
17 / 5 = 3 remainder 2
Tuples in loops and collections
Tuples work nicely inside vectors and for loops. You can destructure right in the loop header:
fn main() {
let scores = vec![("Ivy", 88), ("Leo", 92), ("Sam", 75)];
for (name, score) in &scores {
let grade = if *score >= 90 { "A" } else if *score >= 80 { "B" } else { "C" };
println!("{:<4} {} -> {}", name, score, grade);
}
// swapping two variables with a tuple
let (mut a, mut b) = (1, 2);
(a, b) = (b, a);
println!("a = {}, b = {}", a, b);
}Ivy 88 -> B
Leo 92 -> A
Sam 75 -> C
a = 2, b = 1
The unit type ()
A tuple with zero elements, (), is called the unit type. It means "no meaningful value". A function with no -> Type actually returns (). You will see it in error messages and in Result<(), E> later in the course.
Tuple or struct?
| Use a tuple when… | Use a struct when… |
|---|---|
| there are only 2–3 values | there are many fields |
the meaning is obvious from context, like (x, y) |
names make the code clearer |
| the grouping is temporary, e.g. a return value | the data is a core concept of your program |
Tip: If you find yourself writing comments like
// .2 is the email, it is time to switch to a struct.
Test yourself
How do you read the second element of tuple t?
- t[1]
- t.1
- t.get(1)
- t(1)
What is true about tuples?
- All elements must have the same type
- They can grow with push()
- Elements can have different types, but the length is fixed
- They are always stored on the heap
What is () in Rust?
- A syntax error
- The unit type, meaning no meaningful value
- An empty array
- A null pointer