Skip to content

Go (Golang) 7 - Loops

Published:

Loops are crucial in programming as they allow code to run multiple times. In Go, you can write loops in different ways, but they all use the for keyword.

Writing loops in go

Three-component loop

This loop in Go works similarly to loops in other languages like C or JavaScript:

for i := 0; i < 10; i++ {
	fmt.Println(i)
}

/* Output
 0
 2
 3
 4
 5
 6
 7
 8
 9
*/

This example prints the numbers 0-9. Once i is no longer less than 10, the loop stops.

Simplifying loops

Sometimes, you don’t need to use all three parts of a loop, which allows you to create different loop patterns. For instance, you might skip the initialization or the increment step.

Skipping the Initialization

If the initial value is calculated before the loop starts, you might skip the initialization in the loop itself.

i := 0
for ; i < 10; i++ {
    fmt.Println(i)
}

/* Output
 0
 2
 3
 4
 5
 6
 7
 8
 9
*/
Skipping the Increment Step

When the increment rules are more complex, you might leave out the increment step in the loop header.

for i := 0; i < 10; {
    fmt.Println(i)
    if i < 5 {
        i += 2
    } else {
        i += 3
    }
}

/* Output
 0
 2
 4
 6
 9
*/

This way, you handle the increment inside the loop based on specific conditions.

While loop

In Go, you can create a while loop using the for keyword by skipping the initialization and increment steps.

number := 1
for number <= 10 {
        fmt.Println(number)
        number++;
}

/* Output
 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 */

This example shows a simple while loop where the number starts at 1 and increases until it exceeds 10.

Infinite loop

To create an infinite loop, you can leave out all three parts of the for loop.

for {
    fmt.Println("This loop will run forever.")
}

/* Output
 This loop will run forever.
 This loop will run forever.
 This loop will run forever.
 This loop will run forever.
 ...
 */

To stop the loop, press Ctrl-c.

Break & continue statements

In Go, the break and continue statements help manage loop execution. Here’s how they work.

Break statement

The break statement stops a loop entirely when a certain condition is met.

for i := 1; i <= 10; i++ {
    if i == 5 {
        break // Stops the loop when i reach 5
    }
    fmt.Println(i)
}
/* Output
 1
 2
 3
 4
 */

In this example, the loop stops before printing 5, because the break command exits the loop once i equals 5.

Continue statement

When the continue statement is triggered it will continue to the next iteration.

for i := 1; i <= 10; i++ {
    if i% 2 == 0 {
        continue // Skips even numbers
    }
    fmt.Println(i)
}

/* Output
 1
 3
 5
 7
 9
 */

Here, continue skips the print statement for even numbers. So, only the odd numbers are printed.

Using break and continue allows you to fine-tune how loops operate, either by ending them early or by skipping parts of their execution.

Iterate over slices

In the previous tutorial, we learned about slices but didn’t cover how to loop through them. Here’s a simple way to do it:

	languages := []string{"Go", "Java", "C", "Python", "Ruby"}

	for i, lang := range languages {
		fmt.Println(i)
		fmt.Println(lang)
	}

/* Output
 0
 Go
 1
 Java
 2
 C
 3
 Python
 4
 Ruby
 */

We use the range keyword to step through each item in the list. The for loop then helps us print each item’s position and name. You can use range keyword for example with strings, arrays, slices, maps.

If you don’t need the item’s position, you can skip it like this.

	languages := []string{"Go", "Java", "C", "Python", "Ruby"}

	for _, lang := range languages {
		fmt.Println(lang)
	}

/* Output
 Go
 Java
 C
 Python
 Ruby
 */

Here, the underscore _ tells Go that we’re not using the index, so it ignores it.

Conclusion

In this tutorial, we learned about different loops in Go. These looping techniques are great tools for handling repetitive tasks efficiently in your Go programs. I hope you enjoyed this tutorial.

Full source code can be found here Github