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
.