Tuple, Array, String and Slice
5 minutes of reading
Tuple
A tuple in Rust can store a collection of values.
let tup: (i32, f64, u8) = (500, 6.4, 1);
You can access each individual value within a tuple using the dot notation.
let tup = (20, 25, 50, (1, 5, 3), true, "Rust");
println!("{}", tup.4); // true
println!("{}", (tup.3).2); // 3
You can assign values inside a tuple to multiple variables at once.
let tup = (20, 25, 40);
let (a, b, c) = tup;
If you want to ignore some of the values, you can assign them to _.
let (_, _, c) = tup;
Array
An array in Rust is a fixed-size container which contains items of one particular data type.
let numbers = [1, 2, 3]; // this creates an array
You can print an array to the terminal using the println! macro.
let numbers = [1, 2, 3];
println!("{:?}", numbers);
// output:
// [1, 2, 3]
There are many ways to iterate through all the items inside an array.
let numbers = [1, 2, 3];
// this creates an iterator from the array using the iter() method and the for loop
for n in numbers.iter() {
    println!("{}", n)
}
// output:
// 1
// 2
// 3
 
// this access each item within the array by using its index and the for loop
for n in 0..numbers.len() {
    println!("{}", numbers[n])
}
// output:
// 1
// 2
// 3
You can specify the type of the items in the array. For example, the following specifies an array of three 32-bit integers.
let numbers: [i32; 3] = [1, 2, 3];
println!("{:?}", numbers);
// output:
// [1, 2, 3]
You can initialize an array with items set to a default value. For example, the following creates an array of 10 integers, each slot is initialized to 2.
let numbers = [2; 10];
println!("{:?}", numbers);
// output:
// [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]