Start learning free

LESSON 113 OF 348 · FOR LOOPS - LOOPING OVER ARRAYS

For Loop - Execution Flow in Rust in Rust

Lesson

Rust uses the brackets ({}) to indicate which lines of code are part of a for loop and which are not.

Take this code for example:

let languages = vec!["Python", "Java", "JavaScript"];

for language in &languages {
  println!("I love {}", language);
  println!("I want to get better at it");
}

Both println! statements are part of the loop since they are written inside the brackets.

This means that both messages will be printed for every language in the languages list. The output of that code would be:

I love Python
I want to get better at it
I love Java
I want to get better at it
I love JavaScript
I want to get better at it

As for this code:

let languages = vec!["Python", "Java", "JavaScript"];

for language in &languages {
  println!("I love {}", language);
}
println!("I want to get better at them");

The println!("I want to get better at them"); is not part of the loop.

This means that only println!("I love {}", language); will be executed for every language in the languages list.

Then, when the for loop is over, the println!("I want to get better at them"); will be executed only once.

The output of this program would be:

I love Python
I love Java
I love JavaScript
I want to get better at them

Execution flow

Lastly, note that the execution of a program always begins on the first line. The code is then executed one line at a time from top to bottom. This is known as execution flow and is the order a program in Rust executes code.

For example, this program:

let fruits = vec!["banana", "apple", "kiwi"];

println!("I'm hungry!");

for fruit in &fruits {
  println!("I'm gonna eat:");
  println!("{}", fruit);
}


println!("I love my life!");

prints:

I'm hungry!
I'm gonna eat:
banana
I'm gonna eat:
apple
I'm gonna eat:
kiwi
I love my life!


Assignment:

Add a for loop inside our code in the editor such that the final program would print:

Today we'll learn about:
Python
Java
JavaScript
Let's code!
STEP 1 OF 1
    Ctrl + Enter to check

    Exercise Create A For Loop in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free