Skip to content

Lesson 4: Control Flow

Big Picture

flowchart TD
    CF["Control flow in Go"] --> IF["if / else if / else<br/>optional init: if x := f(), cond"]
    CF --> SW["switch<br/>no fallthrough by default<br/>multiple values per case"]
    CF --> FOR["for — the ONLY loop"]
    FOR --> F1["classic: for i:=0 → i<10 → i++"]
    FOR --> F2["while-style: for cond"]
    FOR --> F3["infinite: for {}"]
    FOR --> F4["range: for i, v := range col"]
    IF --> BC["break / continue"]
    FOR --> BC
    SW --> BC

Coming from Java/C? There is no while or do-while — for covers every looping need.

Concepts

If-Else

if condition {
    // code
} else if anotherCondition {
    // code
} else {
    // code
}

// With initialization
if x := getValue(); x > 10 {
    // x is scoped to this if block
}

Switch

switch value {
case "a":
    // code
case "b", "c":
    // multiple values
default:
    // fallback
}

For Loops

// Traditional
for i := 0; i < 10; i++ { }

// While-style
for condition { }

// Infinite
for { break }

// Range
for index, value := range collection { }

Code Walkthrough

package main

import "fmt"

func main() {
    if n := 7; n%2 == 0 {
        fmt.Println("even")
    } else {
        fmt.Println("odd") // prints
    }

    for i := 0; i < 3; i++ { fmt.Println(i) }

    for _, v := range []string{"a", "b"} { fmt.Println(v) }

    switch day := "Mon"; day {
    case "Sat", "Sun":
        fmt.Println("weekend")
    default:
        fmt.Println("weekday")
    }
}

Full program: code/04_controlflow.go.

Try it yourself

cd code
go run . controlflow

Exercises

  1. Write a switch with no condition (switch-true) to replace an if/else chain.
  2. Use for range on a string — what do you get for index and value?
  3. Write a loop that skips even numbers using continue.

Check Your Understanding

#

Does Go switch fall through to the next case by default?

#

Which loop keywords exist in Go? (select all that are real Go syntax)