GoGo · Lesson 3 of 8
Control Flow
Go's for loop is its only loop. No while, no do-while. Just for, wearing three different costumes.
Go
package main
import "fmt"
func main() {
// if/else — no parentheses around condition
x := 42
if x > 100 {
fmt.Println("large")
} else if x > 10 {
fmt.Println("medium")
} else {
fmt.Println("small")
}
// if with initialization statement
if n := computeSomething(); n > 0 {
fmt.Println("positive:", n)
} else {
fmt.Println("non-positive:", n)
}
// switch — no fallthrough by default (unlike C)
day := "Monday"
switch day {
case "Saturday", "Sunday":
fmt.Println("weekend")
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday":
fmt.Println("weekday")
default:
fmt.Println("unknown")
}
// switch with no condition (like if/else chain)
n := 7
switch {
case n < 0:
fmt.Println("negative")
case n == 0:
fmt.Println("zero")
default:
fmt.Println("positive")
}
}
func computeSomething() int { return 42 }Go
package main
import "fmt"
func main() {
// Classic for loop
for i := 0; i < 5; i++ {
fmt.Println(i)
}
// for as while
n := 0
for n < 10 {
n += 3
}
fmt.Println(n) // 12
// Infinite loop
// for {
// // break out when ready
// break
// }
// for range — iterate over slices, maps, strings
fruits := []string{"apple", "banana", "cherry"}
for i, v := range fruits {
fmt.Printf("%d: %s\n", i, v)
}
// Ignore index with _
for _, fruit := range fruits {
fmt.Println(fruit)
}
// Range over a map
capitals := map[string]string{
"France": "Paris",
"Japan": "Tokyo",
"UK": "London",
}
for country, capital := range capitals {
fmt.Printf("%s -> %s\n", country, capital)
}
// Range over a string (yields runes)
for i, r := range "Hello" {
fmt.Printf("%d: %c\n", i, r)
}
}