If, For, and Switch
Control Flow in Go
Go keeps control flow simple: there is only one loop keyword, and if/switch have helpful extras.
if with init statement
Go's if can run a short statement before the condition. Variables declared there are scoped to the if/else block:
if err := doWork(); err != nil {
log.Fatal(err)
}Go's only loop: for
Go unifies all loop forms with for:
- Classic:
for i := 0; i < 10; i++ { } - While-style:
for condition { } - Infinite:
for { } - Range:
for i, v := range slice { }
range
Iterates over arrays, slices, maps, strings (runes), and channels. Returns index and value.
switch
Go's switch does not fall through by default. Cases can list multiple values. A switch without a condition behaves like if/else if:
switch {
case x < 0: fmt.Println("negative")
case x == 0: fmt.Println("zero")
default: fmt.Println("positive")
}Key points:
- No parentheses around conditions in if/for/switch.
- Use
fallthroughto explicitly fall through in switch. breakexits a loop;continueskips to the next iteration.
Code Examples
package main
import (
"fmt"
"strconv"
)
func main() {
// if with init statement
inputs := []string{"42", "abc", "100"}
for _, s := range inputs {
if n, err := strconv.Atoi(s); err == nil {
fmt.Printf("%s -> %d\n", s, n*2)
} else {
fmt.Printf("%s -> invalid\n", s)
}
}
// range over map
scores := map[string]int{"Alice": 95, "Bob": 80}
for name, score := range scores {
fmt.Printf("%s: %d\n", name, score)
}
}The init statement in if scopes err to the if/else block. range over a map returns key and value in each iteration.
package main
import "fmt"
func classify(n int) string {
switch {
case n < 0:
return "negative"
case n == 0:
return "zero"
case n < 10:
return "small"
case n < 100:
return "medium"
default:
return "large"
}
}
func dayType(day string) string {
switch day {
case "Saturday", "Sunday":
return "weekend"
default:
return "weekday"
}
}
func main() {
for _, n := range []int{-5, 0, 7, 42, 200} {
fmt.Printf("%d: %s\n", n, classify(n))
}
fmt.Println(dayType("Saturday"))
fmt.Println(dayType("Monday"))
}A switch without a condition is like if/else if — cases evaluate boolean expressions. Multiple values in one case use commas.
Quick Quiz
1. How do you write a while-style loop in Go?
2. Does Go's switch fall through by default?
Was this lesson helpful?