Go Tutorial · Control Flow · Lesson 11 of 30

Go Switch

Switch on values, switch with no condition, and fallthrough.

switch

Go's switch doesn't fall through — no break needed. A case can list several values:

Example 1
package main

import "fmt"

func main() {
	day := "sat"
	switch day {
	case "sat", "sun":
		fmt.Println("Weekend")
	case "fri":
		fmt.Println("Almost weekend")
	default:
		fmt.Println("Weekday")
	}
}

Output

Weekend

Run this on your computer — see “Get Started” for setup.

switch with no condition

switch { ... } is a clean way to write long if/else chains:

Example 2
package main

import "fmt"

func main() {
	for _, score := range []int{95, 82, 40} {
		switch {
		case score >= 90:
			fmt.Println(score, "A")
		case score >= 80:
			fmt.Println(score, "B")
		default:
			fmt.Println(score, "F")
		}
	}
}

Output

95 A
82 B
40 F

Run this on your computer — see “Get Started” for setup.

Use the fallthrough keyword in the rare case you want to continue into the next case. Type switches match on types.

Test yourself

Do Go switch cases fall through to the next case by default?

  1. Yes
  2. No
Show answer

Answer: No