Start learning free

LESSON 114 OF 338 · WHILE LOOPS & FOR LOOPS

Why Loops in Go: Repeating Code Without Copy and Paste

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 fmt.Println, our program might look like this:

fmt.Println("I made a mistake")
fmt.Println("I made a mistake")
fmt.Println("I made a mistake")
fmt.Println("I made a mistake")
fmt.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 1
    Ctrl + Enter to check

    GO · WHILE LOOPS & FOR LOOPS

    Why Loops in Go, explained

    The problem loops solve

    Programs often need to do the same thing many times: print a line, process each item in a list, retry something. Without loops, the only tool you have is to write the code once for every repetition.

    Suppose a teacher asks a student to print I made a mistake five times. With only fmt.Println, the program looks like this:

    fmt.Println("I made a mistake")
    fmt.Println("I made a mistake")
    fmt.Println("I made a mistake")
    fmt.Println("I made a mistake")
    fmt.Println("I made a mistake")
    

    It works, and for five lines it is tolerable. Most of the effort is copy and paste.

    Where it breaks down

    Now change the request. The teacher wants the message 10 times, then 100, then 100000. Every change means more lines, and each pasted line is another chance for a typo or a missed line.

    There are three separate costs:

    • Effort. The code grows in proportion to the number of repetitions. One hundred thousand repetitions means one hundred thousand lines.
    • Errors. If you want to change the message later, you must change it in every line. Miss one and the output is inconsistent.
    • Inflexibility. The number of repetitions is fixed when you write the program. You cannot repeat something as many times as there are items in a slice whose size you do not know yet.

    The third cost is the most serious. Real programs work with data whose size is only known when they run, and straight-line code cannot adapt to that.

    What a loop gives you

    A loop lets you write the repeated code once and say how many times, or under what condition, it should run. The repetition count becomes a number or a condition, which is easy to change, instead of a number of lines of code.

    Go has a single loop keyword, for. It covers every case. A for with just a condition plays the role of a while loop, a for with an init, a condition and a post statement counts, and for ... range walks over a slice. The next lessons introduce these forms one at a time. In this lesson you do not need any of them, because the goal is to feel what life is like without a loop.

    The exercise

    Print I promise to learn coding. five times, using only fmt.Println. Each call prints its text and then ends the line, so five calls give five lines:

    fmt.Println("I promise to learn coding.")
    fmt.Println("I promise to learn coding.")
    fmt.Println("I promise to learn coding.")
    fmt.Println("I promise to learn coding.")
    fmt.Println("I promise to learn coding.")
    

    The output is the sentence five times, one per line. Check that the text matches exactly, including the capital letter and the full stop at the end, because the lesson's tests compare it with the expected output character by character.

    Now imagine the same exercise with 1,000 lines. You would almost certainly make a mistake somewhere, and the program would be hard to read. Keep that feeling in mind when the next lesson shows the loop version, which is three lines long and does not change in size when the count grows.

    Key takeaways

    • Repeating code by copying it costs effort and invites mistakes, and every change must be made in many places.
    • Straight-line code cannot adapt to data whose size is unknown when you write the program.
    • A loop writes the repeated code once and controls the repetition with a number or a condition.
    • In Go, the keyword for every kind of loop is for.
    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free