Collecting stuff together in Rust with Tuples

In our previous article we looked at how arrays work in Rust. In this article, we'll look at another compound type that we can use to manage collections of data in rust: Tuples.

What are tuples?

Tuples are a collection of multiple values of various types but with a fixed length.

Tuples are written like this in rust:

fn main() {
    let product = ("Iphone 13 Pro Max", 1399, true).
}

The example above is a tuple that holds data that describes details about a product - product name, cost and availability.

Let's point out some important features of this tuple:

  • unlike an array in Rust, tuples can hold a variation of elements of different data types.

  • similarly to arrays, the length of tuples cannot change and the values at each position can change but the data type allotted to each position cannot be changed. This means you can change the value of the cost of the product 1399 to another 1499 but not 1499.99.

Destructuring Tuples.

Tuples, like arrays can be destructured. To desctructure a tuple, we'll do this:

let (_, _, is_available) = product;

Rust has a special tuple called a unit tuple that is represented as (). It has no value and is what is returned when a function returns nothing in rust.

Next, we'll be looking at how functions work in Rust and another interesting type in Rust called Enums.