Matching one value against several cases

Often you compare one value with a list of exact options: menu choice 1, 2 or 3, or a day of the week. An else if chain works, but you write choice == again on every line. A switch statement is made for this.

package main

import "fmt"

func main() {
	choice := 2
	switch choice {
	case 1:
		fmt.Println("Small")
	case 2:
		fmt.Println("Medium")
	case 3:
		fmt.Println("Large")
	default:
		fmt.Println("Unknown size")
	}
}

Output:

Medium

Go compares choice with each case from top to bottom. It runs the code of the first case that matches, and then the switch is finished. default runs when no case matches, like the last else of a chain. It is optional, but it is a good place to handle a value you did not expect.

Only one case runs. Some other languages keep going into the cases below the match unless you write break. Go does not do that, so you do not need a break at the end of each case.

Several values in one case

One case can list several values, with commas between them. The case runs when the value matches any of them. A switch also works with strings:

day := "Sun"
switch day {
case "Sat", "Sun":
	fmt.Println("Weekend")
case "Mon", "Tue", "Wed", "Thu", "Fri":
	fmt.Println("Weekday")
default:
	fmt.Println("Not a day")
}

Output:

Weekend

A switch with no value

When switch has a value, each case is an exact value. For ranges, like "90 or more", leave out the value after switch. Then each case holds a full condition, and the first true one runs. This is a tidy way to write an else if chain:

score := 81
switch {
case score >= 90:
	fmt.Println("Grade A")
case score >= 75:
	fmt.Println("Grade B")
default:
	fmt.Println("Grade C")
}

Output:

Grade B

As with else if, the order matters. Put the highest score first.

fallthrough

If you really want the next case to run as well, end a case with fallthrough:

n := 2
switch n {
case 1:
	fmt.Println("one")
case 2:
	fmt.Println("two")
	fallthrough
case 3:
	fmt.Println("three")
case 4:
	fmt.Println("four")
}

Output:

two
three

n is 2, but three is printed too. fallthrough does not check the next case's value. It simply runs that case's code. Case 3 has no fallthrough, so the switch stops there and four is not printed. You will rarely need fallthrough. A case with several values is almost always clearer.

A common mistake

Two cases cannot have the same value. Go finds this before the program runs:

package main

import "fmt"

func main() {
	n := 2
	switch n {
	case 1, 2:
		fmt.Println("low")
	case 2, 3:
		fmt.Println("middle")
	}
}

Output:

# command-line-arguments
./main.go:10:7: duplicate case 2 (constant of type int) in expression switch
	./main.go:8:10: previous case

The message names line 10, where 2 appears a second time, and line 8, where it was first used.

In the exercise, finish a switch that turns a month number into a season, using cases with several values.