- What is an array❔
- Declaring an array
- Accessing an array
- Iterating over an array🔁
- Specifying the type and the length of an array
- Default values for arrays
An array is a collection of items of the same type. It is similar to tuples, but tuples can contain different types of items.
To declare an array, we use the []
brackets, and the different items separated by commas.
let objetcs_array = ['👓', '👕', '🧽', '🩴', '🧲'];
To access an item in an array, we use the index of the item.
println!("I like {} and {}", objects_array[0], objects_array[1]);
Output:
I like 👓 and 👕
To iterate over an array, we use the .iter()
method in a for loop.
for item in objects_array.iter() {
println!("I bought a {}", item);
}
Output:
I bought a 👓
I bought a 👕
I bought a 🧽
I bought a 🩴
I bought a 🧲
To iterate over an array, we can use the .len()
method to get the length of the array.
for i in 0..objects_array.len() {
println!("I bought a {}", objects_array[i]);
}
Output:
I bought a 👓
I bought a 👕
I bought a 🧽
I bought a 🩴
I bought a 🧲
We can specify the type and the length of an array when we declare it by adding :
and the types and the length separated by semicolons : [type; length]
.
let objects_array: [str; 5] = ["👓", "👕", "🧽", "🩴", "🧲"];
We can create an array, we can fill a specific range of indexes with a default value.
let penguins_army = ['🐧'; 20];
We just created an array of 20 penguins.
To see what our array looks like, we will have to use a different jocker in the println! statement.
println!("{:?}", penguins_army);
ℹ️ The
:?
is a jocker that prints the array like we would see it in the code.
Output:
['🐧', '🐧', '🐧', '🐧', '🐧', '🐧', '🐧', '🐧', '🐧', '🐧', '🐧', '🐧', '🐧', '🐧', '🐧', '🐧', '🐧', '🐧', '🐧', '🐧']
And we can see that we have an army of penguins 🔫🐧.