Knaph

Control Flow and Functions20 of 621 min read

For

for — Go's only loop

Go has one loop keyword, and it covers every case other languages split across for, while, and do-while.

The classic three-part form:

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

Drop the init and post clauses and it's a while loop:

n := 10
for n > 0 {
	fmt.Println(n)
	n--
}
Go

Drop the condition too and it loops forever, until something inside breaks out:

for {
	// runs until a break
}
Go

And for ... range iterates over slices, arrays, maps, and strings:

names := []string{"Ada", "Grace", "Haleh"}
for i, name := range names {
	fmt.Println(i, name)
}
Go

If you only need the value, discard the index with _ — Go requires you to explicitly acknowledge an unused loop variable, not just leave it dangling:

for _, name := range names {
	fmt.Println(name)
}
Go

Test your understanding

Sign in to test your understanding of this lesson and track your progress.

Builds on

This lesson

Ask an AI

Open a ready-made prompt in ChatGPT or Claude — just press Enter.