Control Flow
Go strips control flow down to the essentials, there's no while, no ternary operator, and if never needs parentheses around its condition.
xp := 45
if xp >= 100 {
fmt.Println("Level up!")
} else if xp >= 50 {
fmt.Println("Almost there")
} else {
fmt.Println("Keep going")
}
for is Go's only loop
Go has exactly one looping keyword, for, used in several shapes:
for i := 0; i < 5; i++ { // classic three-part form
fmt.Println(i)
}
count := 0
for count < 3 { // this IS Go's while loop
count++
}
for { // infinite loop, until an explicit break
break
}
scores := []int{90, 85, 77}
for i, score := range scores { // like Python's enumerate
fmt.Println(i, score)
}
range gives you both the index and value on each iteration, if you only need the value, discard the index with _: for _, score := range scores.
switch
switch {
case xp >= 100:
fmt.Println("Gold")
case xp >= 50:
fmt.Println("Silver")
default:
fmt.Println("Bronze")
}
Unlike C or Java, a Go switch case does not fall through to the next one automatically, each case breaks on its own by default, removing a very common source of bugs.