Go Tutorial menu

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

go
package main

import "fmt"

func main() {
	for i := 1; i <= 5; i++ {
		fmt.Println("Lesson", i)
	}
}
Output
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
PartExampleMeaning
Starti := 1Runs once before the loop
Conditioni <= 5Checked before every round
Stepi++Runs after every round

for as a while Loop

Go has no while keyword. Write for with only a condition:

Example

go
package main

import "fmt"

func main() {
	savings := 0
	months := 0
	for savings < 10000 {
		savings += 3000
		months++
	}
	fmt.Println("Saved", savings, "in", months, "months")
}
Output
Saved 12000 in 4 months

Infinite Loops and break

A for with nothing after it runs forever, until break stops it:

Example

go
package main

import "fmt"

func main() {
	n := 1
	for {
		n *= 2
		if n > 50 {
			break
		}
	}
	fmt.Println(n)
}
Output
64

continue

continue skips the rest of the current round and moves to the next one:

Example

go
package main

import "fmt"

func main() {
	for i := 1; i <= 10; i++ {
		if i%2 == 0 {
			continue
		}
		fmt.Print(i, " ")
	}
	fmt.Println()
}
Output
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

go
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()
}
Output
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

go
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()
	}
}
Output
1	2	3	
2	4	6	
3	6	9	

Exercise

Exercise

How do you write a while-style loop in Go?

Learn Go with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp