Go Loops
Go has only one loop keyword, for, but it can be written in several ways.
The Classic for Loop
It has three parts, separated by semicolons: a start, a condition, and a step.
Example
package main
import "fmt"
func main() {
for i := 1; i <= 5; i++ {
fmt.Println("Lesson", i)
}
}Lesson 1 Lesson 2 Lesson 3 Lesson 4 Lesson 5
| Part | Example | Meaning |
|---|---|---|
| Start | i := 1 | Runs once before the loop |
| Condition | i <= 5 | Checked before every round |
| Step | i++ | Runs after every round |
for as a while Loop
Go has no while keyword. Write for with only a condition:
Example
package main
import "fmt"
func main() {
savings := 0
months := 0
for savings < 10000 {
savings += 3000
months++
}
fmt.Println("Saved", savings, "in", months, "months")
}Saved 12000 in 4 months
Infinite Loops and break
A for with nothing after it runs forever, until break stops it:
Example
package main
import "fmt"
func main() {
n := 1
for {
n *= 2
if n > 50 {
break
}
}
fmt.Println(n)
}64
continue
continue skips the rest of the current round and moves to the next one:
Example
package main
import "fmt"
func main() {
for i := 1; i <= 10; i++ {
if i%2 == 0 {
continue
}
fmt.Print(i, " ")
}
fmt.Println()
}1 3 5 7 9
Looping with range
range goes through each item of a slice, string or map. It gives two values: the index (position) and the value.
Example
package main
import "fmt"
func main() {
cities := []string{"Karachi", "Lahore", "Peshawar"}
for i, city := range cities {
fmt.Println(i, city)
}
for _, city := range cities {
fmt.Println("Visit", city)
}
for i := range 3 {
fmt.Print(i, " ")
}
fmt.Println()
}0 Karachi 1 Lahore 2 Peshawar Visit Karachi Visit Lahore Visit Peshawar 0 1 2
- If you do not need the index, write
_(the blank identifier). Go does not allow unused variables. range 3(Go 1.22 and newer) counts 0, 1, 2.
Looping over a string with range gives you characters (runes), not bytes. This matters for Urdu or other non-English text.
Nested Loops
A loop inside another loop is useful for tables and grids:
Example
package main
import "fmt"
func main() {
for i := 1; i <= 3; i++ {
for j := 1; j <= 3; j++ {
fmt.Print(i*j, "\t")
}
fmt.Println()
}
}1 2 3 2 4 6 3 6 9
Exercise
Exercise
How do you write a while-style loop in Go?
