Rust - Data Types: Collections

1 minute read


:information_source: Note: Read the offical docs to get the most updated information.

Data Types: Collections

Summary:

let my_tuple = (500, 6.4, 1);
let my_array = [1, 2, 3, 4];

Compound types

Rust has two primitive compound types: tuples and arrays, which can group multiple values into one type.

Tuples

Tuples have a fixed length: once declared, they cannot grow or shrink in size.

We create a tuple with (,) The types of the different values in the tuple don’t have to be the same.

let tup: (i32, f64, u8) = (500, 6.4, 1);

let (x, y, z) = tup;
let five_hundred = tup.0;

println!("The value of y is: {y}, five_hundred is {five_hundred}");
  • To get the individual values out of a tuple, we can use pattern matching to destructure a tuple value.
  • This is called destructuring because it breaks the single tuple into three parts.
  • We can also access a tuple element directly by using a period . followed by the index of the value we want to access.
  • The tuple without any values is a unit written as (). Expressions implicitly return the unit value.

Arrays

Every element of an array must have the same type and have a fixed length.

let a: [i32; 5] = [1, 2, 3, 4, 5];
// After the semicolon, 5 indicates the array contains five elements
let b = [3; 5]; // let a = [3, 3, 3, 3, 3];

let first = a[0];
  • If the index is greater than or equal to the length, Rust will panic at runtime.

Updated:

Leave a Comment