Ad space (banner)
๐ŸนGo Lessons
Lesson 5 / 68

Loops (for statements)

In this lesson you will learn how to repeat work with a for statement in Go so you can run the same logic efficiently. This is for anyone searching for "Go for loop how to use".

Go has only the for statement (a for statement stands in for a while loop). Instead of writing the same lines over and over, a few lines express a large number of repetitions - that is the power of a loop.

The sample code prints numbered messages from 1 to 5 using for i := 1; i <= 5; i++. There is no separate while or do-while to learn, and keeping to a single form is characteristically Go: simplicity through having one way to do it.

A common stumbling block for beginners is that the while statement they know from other languages does not exist in Go. You need to understand that a for statement with only a condition takes its place. Combined with the range form, iterating over a slice or a map is simple too.

In real-world development the for statement is one of the most frequently used constructs, for processing lists and for running a fixed number of repetitions alike.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)