Start learning free

LESSON 123 OF 414 · WHILE LOOPS & FOR LOOPS

Why Loops in Rust: Repeating Code Without Copying It

Lesson Read the full explanation

Loops are probably the most powerful tool a programming language can offer. You can run the same code multiple times by using a loop.

To really understand their value, let's take some time to see how frustrating our life would be if a repeated task required us to type out the same code every single time.

Imagine this: A student made a mistake and the teacher asked them to print I made a mistake 5 times to the console.

If we only use println!, our program might look like this:

println!("I made a mistake");
println!("I made a mistake");
println!("I made a mistake");
println!("I made a mistake");
println!("I made a mistake");

That's ugly, but still manageable. After all, we're writing only 5 lines of code and most probably copying and pasting a few times.

Now imagine if we come back to this program and we wanted to print the message for 10, 100, 100000 times? It would take an extremely long time and by the end, we could still end up with inconsistencies and mistakes.

We'll learn how loops come to our rescue in the next lesson. But for now, let's gain an appreciation for loops.


Assignment
Follow the Coding Tutorial to see how frustrating our life is without loops.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    RUST · WHILE LOOPS & FOR LOOPS

    Why Loops in Rust, explained

    What a loop is for

    A loop runs the same piece of code more than once. Almost every real program needs this: handling every item in a list, retrying until something works, counting up to a number. Before learning the syntax, it helps to feel the problem that loops solve.

    Suppose a student has to print I promise to learn coding. five times. With only println!, the program is five identical lines:

    println!("I promise to learn coding.");
    println!("I promise to learn coding.");
    println!("I promise to learn coding.");
    println!("I promise to learn coding.");
    println!("I promise to learn coding.");

    Each line is a statement, and the program runs them from top to bottom, so the message is printed five times, once per line. This is the exercise in the lesson, and it works. The problem appears when the requirements change.

    Why repeating lines does not scale

    Five lines are easy to copy and paste. Now imagine the teacher asks for 100 lines, or 100,000. Several things go wrong:

    • It takes long to write. The number of lines grows with the number of repetitions.
    • It is easy to get wrong. Count the lines in a pasted block of 100 and you will find it hard to be sure there are exactly 100.
    • Changing it is a chore. If the message must change from I promise to learn coding. to something else, you must edit every copy. Miss one, and the output is inconsistent.
    • The count is hidden. Nothing in the code says "five". The number lives only in how many lines you happened to paste.

    Programmers have a rule of thumb for this: if you copy and paste the same code more than a couple of times, something is missing. What is missing is a way to say "do this, and repeat it as many times as needed" once, with the count written as a number.

    What a loop looks like

    You will meet two loops in this chapter. The while loop repeats as long as a condition is true. The for loop repeats once for each value in a range or a collection. Here is a preview of the same five messages written with a for loop over the range 0..5, which holds the numbers 0, 1, 2, 3 and 4:

    for _ in 0..5 {
        println!("I promise to learn coding.");
    }

    It prints the same five lines. The message appears once in the code, and the count appears once too. To print it 100,000 times, you change 5 to 100000 and nothing else. To change the message, you edit one line.

    The underscore _ says that the loop does not use the number it counts with. Do not worry about the details yet: the next lessons explain how each kind of loop works, step by step.

    The exercise

    This lesson asks you to do it the hard way on purpose. Use println! to print I promise to learn coding. five times, with no loop. The solution is just the statement five times:

    println!("I promise to learn coding.");
    println!("I promise to learn coding.");
    println!("I promise to learn coding.");
    println!("I promise to learn coding.");
    println!("I promise to learn coding.");

    A few details are worth noticing, because they come back in every loop lesson:

    • println! ends with an exclamation mark because it is a macro, not an ordinary function. The ! is part of its name, and leaving it out is a compile error.
    • Each println! adds a newline, so every message appears on its own line.
    • Each statement ends with a semicolon.
    • The text between the quotes must match exactly, including the capital I, the spaces and the full stop at the end. A message that differs by one character is a different message, and the lesson's tests compare the output exactly.

    Common mistakes

    • Printing the wrong number of times. With five pasted lines it is easy to end up with four or six. This is the weakness of the approach, and a good reason to use a loop when the count matters.
    • Forgetting the ! after println. The compiler reports expected function, found macro and suggests adding the !.
    • Typos in one copy. If one line has a small difference, the output is no longer five identical lines.

    Key takeaways

    • A loop runs the same code several times, so you write it once.
    • Repeating statements by hand is slow, error-prone and hard to change.
    • A loop states the count as a number, so going from 5 repetitions to 100,000 is a one-number edit.
    • Rust has while loops, which repeat while a condition holds, and for loops, which repeat once per value in a range or collection. The next lessons teach both.
    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free