Go Control Statements

Go if, switch, and for statements

if Statement

if condition { processing } executes the processing only when the condition is true. The condition does not need parentheses ((...)), but the processing must be enclosed in braces ({ ... }).

if x > y {
    fmt.Println("x is greater than y")
}

You can use else or else if.

if x > y {
    fmt.Println("Big")
} else if x < y {
    fmt.Println("Small")
} else {
    fmt.Println("Equal")
}

switch Statement

switch expression { ... } selects processing according to the value of an expression.

switch mode {
case "running":
    fmt.Println("Running")
case "stop":
    fmt.Println("Stopped")
default:
    fmt.Println("Unknown")
}

With switch { ... }, each case can specify a condition.

switch {
case x > y:
    fmt.Println("Big")
case x < y:
    fmt.Println("Small")
default:
    fmt.Println("Equal")
}

Unlike many other languages, Go does not require a break statement. To continue into the next case, use fallthrough.

The following example prints "Holiday" when dayOfWeek is "Sat" or "Sun".

switch dayOfWeek {
case "Sat":
    fallthrough
case "Sun":
    fmt.Println("Holiday")
default:
    fmt.Println("Weekday")
}

for Statement

Go does not have a while statement. All loops use for.

The following example repeats while x is less than y.

for x < y {
    x++
}

for initialization; condition; post-processing { processing } first performs initialization, then repeats processing and post-processing while the condition is true.

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

Omitting the condition creates an infinite loop. continue starts the next iteration, and break exits the loop.

package main

import "fmt"

func main() {
	n := 0
	for {
		n++
		if n > 10 {
			break
		} else if n%2 == 1 {
			continue
		} else {
			fmt.Println(n)
		}
	}
}

Output:

2
4
6
8
10

Use range to loop over iterable values such as arrays and slices.

package main

import "fmt"

func main() {
	colors := [...]string{"Red", "Green", "Blue"}

	for i, color := range colors {
		fmt.Printf("%d: %s\n", i, color)
	}
}

Output:

0: Red
1: Green
2: Blue