Go Fundamentals

Lesson 3 of 8

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.

📝 Control Flow Quiz

Passing score: 70%
  1. 1.Which keyword is used for every kind of loop in Go, including a "while"-style loop?

  2. 2.A Go switch case automatically falls through to the next case unless you add a break.

  3. 3.Iterating with "for i, v := range items" gives you both the index and the ____ on each pass.