Day 5 - Compound Types

Rust have two primitive types that can group multiple values in one type:
Tuples
Arrays
Both have fixed size, that means that once they are declared they cannot grow or shrink in size.
Tuples
Tuples are used to group values with distinct types. Tuples are created writing comma-separated list of values inside parentheses.
let tuple = (1, 2.3, 'a');
let tuple2: (i8, char, f64) = (0, 'z', 3.1416);
Tuples can be destructured using pattern matching:
let tuple3 = (1, 2.3, 'a');
let (x, y, z) = tuple3
// x = 1
// y = 2.3
// z = 'a'
Elements from a tuple could also be accessed using by their index using a period:
let tuple3 = ('a', 2, 0.3);
let second = tuple3.1;
// second = 2
Arrays
An array in Rust is a collection of multiple values. Unlike tuples, values in an array must be all the same type.
An array is created writing comma-separated values (all same type) inside square brackets:
let a = [0, 1, 2, 3, 4];
You can also declare type and size of the array:
let vowels: [char, 5] = ['a', 'e', 'i', 'o', 'u'];
An array could be initialized with same value for all the elements:
let zeroes = [0, 3];
// zeroes = [0, 0, 0)
Elements in an array could be accessed through index:
let vowels: [char, 5] = ['a', 'e', 'i', 'o', 'u'];
let letter_e = vowels[1];
// letter_e = 'e'
Now that you know how to group values, let’s learn how to control the flow of your program. Day 6 is all about logic and decisions.
Subscribe to my newsletter
Read articles from Juan Horta directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
