Loops, range and labels
Go has one loop keyword, for, and four shapes: a counter, a condition, a range over a value, and the bare for that loops until something stops it. There is no while and no do while, because the condition form covers both.
The four shapes
The counter form is the C loop without parentheses. The condition form drops the counter entirely. The bare form needs a break or a return, and Go 1.22 added for i := range 3, which counts without a slice to range over.
package main
import "fmt"
func main() {
sum := 0
for i := 0; i < 5; i++ {
sum += i
}
fmt.Println("sum:", sum)
n := 0
for n < 3 {
n++
}
fmt.Println("n:", n)
for i := range 3 {
fmt.Print(i, " ")
}
fmt.Println()
count := 0
for {
count++
if count == 2 {
break
}
}
fmt.Println("infinite loop stopped at", count)
}
go run forms.go
sum: 10
n: 3
0 1 2
infinite loop stopped at 2
The variables of a counter loop exist only inside it. break leaves the innermost loop and continue starts its next iteration; both take an optional label, which the last section uses.
range
range walks a slice, an array, a string, a map or a channel. Over a string it yields the byte offset and the rune, so a multi-byte character counts as one iteration and the index jumps by its length; over a map the order is deliberately random.
package main
import "fmt"
func main() {
words := []string{"go", "is", "fun"}
for i, w := range words {
fmt.Println(i, w)
}
for _, r := range "héllo" {
fmt.Printf("%c ", r)
}
fmt.Println()
scores := map[string]int{"go": 2, "c": 1}
total := 0
for name, score := range scores {
fmt.Println(name, score)
total += score
}
fmt.Println("total:", total)
}
go run range.go
0 go
1 is
2 fun
h é l l o
go 2
c 1
total: 3
The map printed go and c in an order the runtime chose, and it may choose another one next time: a program that needs a fixed order sorts the keys first (see sorting). The _ in the second loop discards the index, and the variables lesson explains why the compiler wants it.
Labels
A label before a loop gives break and continue a way to name an outer loop. It is how Go writes "stop the whole search" without a flag variable, and it is also how a goto would be written, though a label on a loop is the readable form.
package main
import "fmt"
func main() {
outer:
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
if j == 2 {
continue outer
}
if i == 2 {
break outer
}
fmt.Println(i, j)
}
}
fmt.Println("done")
}
go run labels.go
0 0
0 1
1 0
1 1
done
continue outer jumps to the next iteration of the outer loop, so the j == 2 case never prints. break outer leaves both loops at once when i == 2.
break outside a loop
break also leaves a switch or a select. Outside all three it is a compiler error, and the message names the three statements.
package main
import "fmt"
func main() {
fmt.Println("before")
break
}
go build outside.go
# command-line-arguments
./outside.go:7:2: break is not in a loop, switch, or select
Exercises
- Print the multiplication table with two nested loops and a labelled break that stops at the diagonal.
- Count the runes and the bytes of a string with one range loop and one len call. Which number is larger for a non-ASCII text?
- Write the same sum with for i := range 100 and with for i := 0; i < 100; i++. Which one does gofmt keep as it is?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which keyword does Go use for a while loop?
Answer
for, with a condition
Go has one loop keyword, and the condition form is the while loop.
-
What does
for i := range 3iterate?Answer
The integers 0, 1 and 2
Ranging over an integer yields 0 up to n-1, added in Go 1.22.
-
What does range over a string yield?
Answer
The byte offset and the rune
The index is a byte offset, and the value is a rune, so a multi-byte character is one iteration.
-
In which order does range walk a map?
Answer
A random order the runtime chooses
The order is deliberately unspecified, and a program that needs one sorts the keys.
-
What does this program print?
package main import "fmt" func main() { s := 0 for i := 1; i <= 4; i++ { s += i } fmt.Println(s) }Answer
10
The loop adds 1, 2, 3 and 4.
-
What does this program print?
package main import "fmt" func main() { for i := 0; i < 5; i++ { if i == 3 { break } fmt.Print(i) } fmt.Println() }Answer
012
break leaves the loop before 3 is printed.
-
What does this program print?
package main import "fmt" func main() { for i := 0; i < 5; i++ { if i%2 == 0 { continue } fmt.Print(i) } fmt.Println() }Answer
13
continue skips the even iterations, so only 1 and 3 are printed.
-
What does the compiler say about
breakoutside a loop?Answer
break is not in a loop, switch, or select
The message names the three statements break may leave.
-
Why does a program sort map keys before printing?
Answer
Because range order is random
The runtime randomises the start of a map iteration to stop code depending on an order.
-
What does a label before a loop do?
Answer
It lets break and continue name that loop
break label and continue label act on the named loop.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev