Golang: Switch (conditional)

By Xah Lee. Date: . Last updated: .

Switch-Statement

Switch-statement lets you test if a condition is met. It goes thru multiple case-statements, if true, that case's statement is executed, and switch exits.

package main

import "fmt"

func main() {
	switch 3 {
	case 4:
		fmt.Println("aa")
	case 3:
		fmt.Println("bb")
	default:
		fmt.Println("dd")
	}
}

// bb

case fallthrough

A case body can end with fallthrough. If so, the rest cases are run.

package main

import "fmt"

func main() {
	switch 3 {
	case 4:
		fmt.Println("aa")
	case 3:
		fmt.Println("bb")
		fallthrough
	default:
		fmt.Println("dd")
	}
}

// prints:
// bb
// dd

multiple tests in 1 case shortcut

Multiple tests can be combined in one case statement, separated by comma ,.

package main

import "fmt"

func main() {
	switch 3 {
	case 4:
		fmt.Println("aa")
	case 3, 7:
		fmt.Println("bb")
	default:
		fmt.Println("dd")
	}
}

// bb

switch without expression

Switch can be used without expression. If so, each case expression just test for true.

package main

import "fmt"

func main() {
	switch {
	case 4 > 7:
		fmt.Println("aa")
	case 3 > 0:
		fmt.Println("bb")
	default:
		fmt.Println("dd")
	}
}

// bb