- 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 π«π§.
Home π - Next Section βοΈ