The Rust Programming Language — Collections — Tuples
Collections is an important part of Rust. There are multiple kinds of collections in Rust:
- Tuples
- Structs
- Arrays
- Memory
A collection is nothing but a set of values.
When we talk about tuples, imagine an array but with a fixed size. Once the size of the tuple is determined, for example, 3 elements, it [size] cannot be changed throughout the lifecycle of the program. Imagine an array without push/pop method. Tuple is a set of values where the size of the set is fixed. Take for example 2D Graph plotting coordinates (x, y) is a tuple of x and y or 3D Graph plotting coordinates (x, y, z) is a tuple of x, y and z.
Refer the below snippet to see how you can define a tuple:
fn main() {
let point: (i64, i64, i64) = (0, 1, 2);
println!("Point 0: {}", point.0);
println!("Point 1: {}", point.1);
println!("Point 2: {}", point.2);
}Observations:
- Your type of the tuple, i.e.
(i64, i64, i64)determines the size of the tuple i.e.3 - You can access individual values of the tuples using index i.e.
point.0,point.1,point.2.

You can define mutable tuple by adding a mut keyword while declaring the tuple and that will allow you to change the values of the tuple.
fn main() {
let mut point: (i64, i64, i64) = (0, 1, 2);
point.0 = point.0 + 1;
point.1 = point.1 + 1;
point.2 = point.2 + 1;
println!("Point 0: {}", point.0);
println!("Point 1: {}", point.1);
println!("Point 2: {}", point.2);
}
Rust also provides you a shorthand or a de-structuring mechanism for tuples. You can selectively access the values of a tuple. Refer below code snippet for de-structuring example:
fn main() {
let point: (i64, i64, i64) = (0, 1, 2);
let (x, y, z) = point;
println!("x: {}", x);
println!("y: {}", y);
println!("z: {}", z);
let (a, b, _) = point;
println!("a: {}", a);
println!("b: {}", b);
let (d, _, f) = point;
println!("d: {}", d);
println!("f: {}", f);
}Observations:
- De-structuring pattern and size of the tuple should match. For e.g.
(x, y, z)should be of same size as(0, 1, 2). - If you want to ignore a value, you can ignore it using
_.

There is also a unit tuple which is ideally of size 0. As compared to other languages, it represents void in Rust. If a function does not return anything, it means it is returning a unit tuple, i.e. void. Refer below snippet for unit tuple example:
fn main() -> () {
let unit: () = ();
}To re-iterate, we cannot alter the size of the tuples in Rust. We can alter the values of mutable tuple.
I hope you enjoyed this article with the details about tuples. Please share your feedback in the comments.
You can subscribe to my newsletter about The Rust Programming Language here. You can read about all the articles in this series here.






