Mahdi.Kh
September 21, 2026
We get familiar with loops and learn how loops can be used to repeat a set of statements.
Loops let you run a set of statements repeatedly. There's only one kind of loop, the for loop. Even so, this loop can be used in several different ways.
The counting loop has three parts:
Initialization: in this part, a variable is declared and assigned a value. This part runs only once, at the start of the loop.
Condition: the loop's condition is checked before every iteration. If the condition is true, the loop body runs; otherwise, the loop stops.
Post: after every run of the statements inside the loop, this part runs to update the counter variable.
For example, the code below shows the numbers from 1 to 50:
Depending on the situation, each part of the counting loop can be omitted, or moved outside or inside the loop:
If we omit the loop's condition, an infinite loop is created. The code below runs forever, printing the current time to the screen every second:
If your program has an infinite loop that uses a lot of system resources (CPU, RAM, GPU), your program might run into a resource-exhaustion error.
Looping over collections is done using the for range construct, which lets us iterate over collection types such as arrays, maps, slices, strings, and channels. This loop is used to access each element of the collection.
The general structure of this loop is as follows:
If you only need each element's value, you can use _ in place of the index.
If you only need each element's index, you can do the following:
Running the break statement lets you exit the current loop. For example, the loop below shows the numbers 0 to 10 and exits the loop when break runs.
The continue statement causes the code after continue to not run, and moves the loop on to its next step. In the loop below, by running the continue statement, we prevent odd numbers from being shown and display the numbers 0 to 10:
Using a label, you can mark a line of code and then, using the break or continue statements, jump from the innermost loop to where the outer label is:
In the code above, when we call break, we jump from the innermost loop to where we named loop, and because we used the break statement, the execution of every loop along that path ends.
In the example below, we use continue and advance both loops forward by one step:
Loops are used to repeat statements. In Go, we have only one loop, for, but this loop can be used in several different ways.
Previous part: The slice Data Type | Golang basics
Next part: The map Data Type | Golang basics