Rust — Tuples
Group different types together
Tuples bundle a fixed number of values that may have different types:
let person: (&str, i32, bool) = ("Ada", 36, true);
let point = (3.0, 4.0); // (f64, f64)
let mixed = (1, "two", 3.0); // any mix allowed
Like arrays they're fixed-length; unlike arrays each slot can differ in type.
Destructuring — the idiomatic access
Pull values out by pattern:
let person = ("Ada", 36, true);
let (name, age, active) = person;
println!("{} is {} years old", name, age);
Underscore skips slots you don't need:
let (_, score) = ("Ada", 95);
Index by position with dot syntax
let point = (3.0, 4.5);
point.0 // 3.0
point.1 // 4.5
// point.2 ❌ compile error — only two fields exist
Numbers are literals — point.0 not point[i]. No variables as indexes.
Returning multiple values from functions
THE classic use — no wrapper struct needed:
fn min_max(numbers: &[i32]) -> (i32, i32) {
(*numbers.iter().min().unwrap(), *numbers.iter().max().unwrap())
}
let (lo, hi) = min_max(&[4, -2, 9, 1]);
println!("range {}..{}", lo, hi);
Standard library does this everywhere — divmod-style pairs:
let (hours, remainder) = (7384 / 3600, 7384 % 3600);
Swapping without a temp variable
let mut a = 1;
let mut b = 2;
std::mem::swap(&mut a, &mut b); // or the tuple trick:
(a, b) = (b, a);
The unit type ()
A tuple with ZERO elements:
let nothing: () = ();
fn no_return() {} // implicitly returns ()
() is Rust's way of saying "no meaningful value" — what functions return when other languages would say void.
Nested & comparing
let nested = ((1, 2), (3, 4));
nested.0.1 // 2
(1, 2) < (1, 3) // true — compares element by element
(1, 2) == (1, 2) // true — full equality
Comparison walks left to right through members.
When tuple vs struct? Two-three closely-related values passed together → tuple fine. Anything with meaning worth naming or reused in multiple places → give it a real struct.
(f64, f64)as a "point" gets unreadable fast;struct Point { x, y }documents itself.
Mini Practice
- Return (sum, average) from one function over a slice.
- Destructure a 3-tuple ignoring the middle value.
- Swap two numbers via tuple assignment.
- Build a nested pair-of-pairs; access the deepest element.
- Refactor
(i32, i32)coordinates into a struct — compare readability.
Next: HashMap →
Related Topics
Frequently Asked Questions about Tuples
What is Tuples in Rust?
Tuples is a fundamental concept in Rust. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Tuples?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Tuples.
Why is Tuples important in Rust?
Tuples is essential for Rust development. Understanding this concept will help you write better code and solve real-world problems more effectively.