For loops are used to iterate over a given sequence.
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
A vector is a group of values that can be iterated over.
A vector can be declared with the vec!
macro and the values separated by commas.
Example:
let animals = vec!["π Monkey", "π Dog", "π¦ Unicorn"];
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
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 βοΈ