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

Loops (a for statement in place of while)

In this lesson you will learn to use a condition-only for statement in place of a while loop in Go, and understand conditional repetition. This is for anyone searching for "Go while loop alternative".

Go has no while statement; a for statement with only a condition takes its place. Use the full for statement with initialiser, condition, and update when you already know the stopping point, and the condition-only form when you do not.

The sample code initialises i := 1, then uses the condition-only for i <= 5, increasing the value by one with i++ inside the loop. Exiting the moment the condition becomes false behaves exactly like a while loop in other languages.

A common stumbling block for beginners is forgetting to update the variable the condition depends on. Miss that update and you get an infinite loop. When you actually want one, you can drop the condition entirely and write for {}, leaving it with break.

In real-world development, the condition-only for statement is common where the number of repetitions is not known in advance - work that repeats until a condition is met.

๐Ÿ“– 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)