Control flow: if, for and switch
Course contents (17 lessons)
- Getting started with Go
- Installing Go 1.25 and your first program
- Variables, types and constants
- Control flow: if, for and switch
- Functions, multiple returns and defer
- Slices and maps
- Arrays and slices
- Maps and working with strings
- Structs, methods and interfaces
- Structs, methods and pointers
- Interfaces
- Errors, packages and generics
- Error handling the Go way
- Packages and modules
- Generics
- Concurrency
- Goroutines and channels
- select, timeouts and context
- Mutexes, sync and the race detector
- Testing
- Testing and benchmarks
- Building and shipping a service
- Building an HTTP JSON API with net/http
- Building and deploying a Go service
Fewer keywords, same power
Go has only one loop keyword, for, and conditions are written without brackets around them. Braces are always required, even for a single line.
if and else
age := 20
if age >= 18 {
fmt.Println("adult")
} else if age >= 13 {
fmt.Println("teen")
} else {
fmt.Println("child")
}
The condition must be a real bool. Unlike in some languages, if count { does not work with a number. Write if count != 0 {.
An if can start with a short statement, whose variables exist only inside the if and its else branches. You will see this form constantly with error handling:
if n, err := strconv.Atoi("42"); err != nil {
fmt.Println("not a number:", err)
} else {
fmt.Println("number is", n)
}
for: the only loop
package main
import "fmt"
func main() {
// 1. classic three-part loop
for i := 0; i < 3; i++ {
fmt.Println("invoice", i)
}
// 2. condition only: like while
stock := 10
for stock > 0 {
stock -= 4
}
fmt.Println("stock now", stock)
// 3. range over a slice
prices := []float64{250, 400, 175}
total := 0.0
for index, price := range prices {
fmt.Printf("%d: %.0f\n", index, price)
total += price
}
fmt.Println("total", total)
// 4. range over an integer (Go 1.22+)
for n := range 3 {
fmt.Print(n, " ")
}
fmt.Println()
// 5. infinite loop with break and continue
count := 0
for {
count++
if count%2 == 0 {
continue
}
if count > 7 {
break
}
fmt.Print(count, " ")
}
fmt.Println()
}
Output:
invoice 0
invoice 1
invoice 2
stock now -2
0: 250
1: 400
2: 175
total 825
0 1 2
1 3 5 7
Walking through the forms
The first form has an initialiser, a condition and a step, like in C. The second has only a condition and acts as a while loop. The third uses range, which gives the index and the value for slices, arrays, strings and maps. If you do not need the index, replace it with the blank identifier _: for _, price := range prices. If you only need the index, just write for i := range prices.
The fourth form, range 3, is newer. Since Go 1.22 you can range over an integer and get 0, 1, 2. It is cleaner than the classic loop for simple counts. The last form has no condition at all: an infinite loop that you leave with break. continue skips to the next round.
A change in Go 1.22 worth knowing
Before Go 1.22, the loop variable was shared between all iterations, and closures or goroutines started inside a loop could all see the last value. This was a famous source of bugs. Since Go 1.22, each iteration gets its own copy of the variable, and the problem is gone, as long as your go.mod says go 1.22 or later. You will see old advice about copying the variable (i := i). With Go 1.25 you do not need it.
switch
switch compares a value against cases and runs the first match. There is no fall-through between cases, so you do not write break.
day := "Sat"
switch day {
case "Sat", "Sun":
fmt.Println("weekend")
case "Fri":
fmt.Println("almost")
default:
fmt.Println("weekday")
}
weight := 3.5
switch { // no value: each case is a condition
case weight <= 1:
fmt.Println("Rs 200")
case weight <= 5:
fmt.Println("Rs 450")
default:
fmt.Println("Rs 450 + extra")
}
A case can list several values separated by commas. A switch without a value is a clean replacement for a long if / else if chain, with the first true case winning, so put narrow conditions first. If you really want to continue into the next case, write fallthrough, but it is rare.
Labels
To break out of a nested loop, put a label before the outer loop and use it: break outer. Use this sparingly. Often a small function with a return is clearer.
Common mistakes
- Forgetting that range gives a copy. Changing
priceinsidefor _, price := range pricesdoes not change the slice. Assign through the index:prices[i] = .... - Brackets around conditions. They are allowed but unusual, and
gofmtremoves them. - Expecting
breakin a switch inside a for loop to leave the loop. It leaves only the switch. Use a label or a return. - Modifying a slice while ranging over it. Range takes its length at the start. Appending inside does not extend the loop.
Try it yourself
Write a program that prints the numbers from 1 to 30. For multiples of 3 print "Fizz", for multiples of 5 print "Buzz", and for multiples of both print "FizzBuzz". Do it with a for and a switch with no value. Then make a second version using range 30 and notice the off-by-one adjustment you need.
package main
import "fmt"
func main() {
// 1. classic three-part loop
for i := 0; i < 3; i++ {
fmt.Println("invoice", i)
}
// 2. condition only: like while
stock := 10
for stock > 0 {
stock -= 4
}
fmt.Println("stock now", stock)
// 3. range over a slice
prices := []float64{250, 400, 175}
total := 0.0
for index, price := range prices {
fmt.Printf("%d: %.0f\n", index, price)
total += price
}
fmt.Println("total", total)
// 4. range over an integer (Go 1.22+)
for n := range 3 {
fmt.Print(n, " ")
}
fmt.Println()
// 5. infinite loop with break and continue
count := 0
for {
count++
if count%2 == 0 {
continue
}
if count > 7 {
break
}
fmt.Print(count, " ")
}
fmt.Println()
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account