Knaph

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)
}

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

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

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

for {
	// runs until a break
}

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

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

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)
}

Sign in to track your progress through this course.

Ask an AI

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

SummarizeChatGPTClaude
Ask me questionsChatGPTClaude
Let's learn togetherChatGPTClaude