Go: Switch statement

A switch statement is a shorter way to write a sequence of if-else statements.

Basics

switch time.Now().Weekday() {
case time.Saturday:
        fmt.Println("Today is Saturday.")
case time.Sunday:
        fmt.Println("Today is Sunday.")
default:
        fmt.Println("Today is a weekday.")
}

Unlike C and Java, the case expressions do not need to be constants. They can be arbitrary expressions as will be seen in the section below.

No condition

hour := time.Now().Hour()
switch { // Same as: switch true
case hour < 12:
        fmt.Println("Good morning!")
case hour < 17:
        fmt.Println("Good afternoon!")
default:
        fmt.Println("Good evening!")
}

Case lists

func whiteSpace(c rune) bool {
    switch c {
    case ' ', '\t', '\n', '\f', '\r':
        return true
    }
    return false
}

Fall through

switch 2 {
case 1:
        fmt.Println("1")
        fallthrough
case 2:
        fmt.Println("2")
        fallthrough
case 3:
        fmt.Println("3")
}
2
3

Exit a switch

A break statement terminates execution of the innermost for, switch, or select statement.

Execution order

func Foo(n int) int {
        fmt.Println(n)
        return n
}

func main() {
        switch Foo(1) {
        case Foo(0), Foo(1), Foo(2):
                fmt.Println("First case")
                fallthrough
        case Foo(3):
                fmt.Println("Second case")
        }
}
1
0
1
First case
Second case

Comments

Be the first to comment!