learn-rust

Free Rust πŸ¦€ course in English πŸ‡¬πŸ‡§

View on GitHub

Table of contentsπŸ“š

Arrays πŸ“œ

What is an array❔

An array is a collection of items of the same type. It is similar to tuples, but tuples can contain different types of items.

Declaring an array

To declare an array, we use the [] brackets, and the different items separated by commas.

let objetcs_array = ['πŸ‘“', 'πŸ‘•', '🧽', '🩴', '🧲'];

Accessing an 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 πŸ‘•

Iterating over an arrayπŸ”

With the iter method

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 🧲

With the length of the array

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 🧲

Specifying the type and the length of an array

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] = ["πŸ‘“", "πŸ‘•", "🧽", "🩴", "🧲"];

Default values for arrays

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 ⏭️


Course created by SkwalExe and inspired by Dcode