HowtoGo
Home / Basics / Control Flow
Basics

Control Flow

Go has three ways to change what runs next: if, for, and switch. Conditions carry no parentheses and bodies always carry braces.

Conditions go unparenthesized, and the braces stay even around a single line. That one rule removes the dangling-else bug and the argument about brace placement in one go.

temp := 31

if temp < 32 {
    fmt.Println("freezing")
} else {
    fmt.Println("above freezing")
}

An if can run a short statement before it tests anything. score lives inside the if and its else, and stops existing after them, which keeps a throwaway value out of the rest of the function.

if score := 88; score >= 80 {
    fmt.Println("passed with", score)
}

for is the only loop keyword in the language. The three-clause form sets a counter, tests it before each turn, and advances it after.

for i := 1; i <= 3; i++ {
    fmt.Println("tick", i)
}

Drop the first and third clauses and you have a while loop. Keep only the condition and the loop runs for as long as it holds.

n := 1
for n < 8 {
    n *= 2
}
fmt.Println(n)

range walks a slice, array, map, string, or channel, handing back the index and the value on each turn.

for i, city := range []string{"Groton", "Mystic"} {
    fmt.Println(i, city)
}

switch tests a value against each case and leaves as soon as one matches. A single case can list several values, and it takes an init statement the same way if does.

switch day := "tue"; day {
case "sat", "sun":
    fmt.Println("weekend")
default:
    fmt.Println("weekday")
}

Leave the value off and every case becomes a plain boolean test. This is the readable shape for a long chain of else if, and it is worth reaching for early.

hour := 14

switch {
case hour < 12:
    fmt.Println("morning")
case hour < 18:
    fmt.Println("afternoon")
default:
    fmt.Println("evening")
}

continue jumps to the next turn of the loop and break leaves it. Both apply to the closest enclosing loop, so reaching an outer one means labeling it.

for i := 1; i <= 5; i++ {
    if i == 2 {
        continue
    }
    if i == 4 {
        break
    }
    fmt.Println("kept", i)
}

The last two lines come from the loop that skipped 2 and stopped once it reached 4.

Terminal
$ go run controlflow.go
freezing
passed with 88
tick 1
tick 2
tick 3
8
0 Groton
1 Mystic
weekday
afternoon
kept 1
kept 3