Reading The Rust Book from cover to cover — Day 4 — Compound Data Types

Jaspreet Kaur
2 min readApr 8, 2024

Rust has two primitive compound types — Tuples and Arrays.

The Tuple Type

A Tuple is a way of grouping multiple values of varying types into a single variable. Tuples have fixed lengths and once declared, tuples can not grow or shrink.

How to create Tuples: by writing a list of comma-separated values inside parentheses. How to create a Tuple:

let tuple1: (i32, f64, u8) = (500, 6.4, 1);
let tuple2 = ('c', 6.4, 1, false); //explicit type annotation is optional

To read values from a Tuple, you can either destructure a Tuple into individual parts like this:

let tuple = ('c', 6.4, 1, false); 
let (x , y, z , a) = tuple;
println!("The values in tuple2 are: {x}, {y}, {z}, {a}");

OR by using a period (.) followed by the index of the value you want to access. For example:

let tuple = ('c', 6.4, 1, false, );
let first_element = tuple.0;
println!("The value of first_element is: {first_element}");

The tuple without any values has a special name, unit.

The Array Type

--

--

No responses yet