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 theenumerate()
method returns a tuple with the index and the value.
Home ๐ - Next Section โญ๏ธ