learn-rust

Free Rust ๐Ÿฆ€ course in English ๐Ÿ‡ฌ๐Ÿ‡ง

View on GitHub

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