Skip to content

Latest commit

Β 

History

History

for-loops

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
Β 
Β 

Table of ContentsπŸ“š

For loopsπŸ”’

What is a for loop❓

For loops are used to iterate over a given sequence.

The for keywordπŸ”‘

The for keyword is used to create a for loop.

Example:

for count in 0..5 {
    println!("πŸ”’ -> {}", count);
}

Here, count is the variable that holds the current value of the loop, and 0..5 is an expression that generates the range of values to iterate over.

0..5 is the range of values from 0 to 5 (5 not included).

Output:

πŸ”’ -> 0
πŸ”’ -> 1
πŸ”’ -> 2
πŸ”’ -> 3
πŸ”’ -> 4

It is possible to store a range in a variable:

let range = 0..5;
for count in range {
    println!("πŸ“’ {}", count);
}

Output:

πŸ“’ 0
πŸ“’ 1
πŸ“’ 2
πŸ“’ 3
πŸ“’ 4

Vector iteration

What is a vector❓

A vector is a group of values that can be iterated over.

Declaring a vector

A vector can be declared with the vec! macro and the values separated by commas.

Example:

let animals = vec!["πŸ’ Monkey", "πŸ• Dog", "πŸ¦„ Unicorn"];

Iterating over a vector

A vector can be iterated over using the for loop.

Example:

let animals = vec!["πŸ’ Monkey", "πŸ• Dog", "πŸ¦„ Unicorn"];

for animal in animals.iter() {
    println!("My πŸ’« favorite animal πŸ’« is the {}", animal);
}

Output:

My πŸ’« favorite animal πŸ’« is the πŸ’ Monkey
My πŸ’« favorite animal πŸ’« is the πŸ• Dog
My πŸ’« favorite animal πŸ’« is the πŸ¦„ Unicorn

ℹ️ We use the iter() method to get an iterator over the vector and to prevent the ownership of the vector from being moved and being able to use it after the loop

Iterating over a vector with indexπŸ”’

It is possible to iterate over a vector knowing the index of the current element.

We can do that with the enumerate() method.

Example:

let fruits = vec!["πŸ‡ Grapes", "🍈 Melons", "🍌 Bananas"];

for (index, fruit) in fruits.iter().enumerate() {
    println!("I love {} at index {}", fruit, index);
}

Output:

I love πŸ‡ Grapes at index 0 
I love 🍈 Melons at index 1
I love 🍌 Bananas at index 2

ℹ️ We use (index, number) because the enumerate() method returns a tuple with the index and the value.


Home 🏠 - Next Section ⏭️


Course created by SkwalExe and inspired by Dcode