Skip to main content

The switch Statement

When a value can lead to one of several different code blocks, a switch statement lets you pick the right one.

If you have used switch in other languages, the Go version will look familiar, with one difference: only the matching case runs. Execution does not carry on into the next case, so you don't write a break at the end of each one.


Single-Case switch Syntax

Go works out the switch expression a single time, then checks the result against each case value. The block under the matching case is the one that runs. You may also add default, which is optional, to supply code for when no case fits.

switch Syntax

main.go
switch expression {
case x:
  // code block
case y:
  // code block
case z:
...
default:
  // code block
}

Single-Case switch Example

Here a number stands for a day of the week, and the switch turns it into that day's name. With day set to 4, the result is Thursday.

Example

Prompt
Use a switch statement with variable day set to 4. Print the weekday name for each case 1-7 (Monday to Sunday).
Output: Go program and captured output

The default Keyword

When none of the cases fit, the code under default takes over. In this example, no case covers the value 8, so the default message is printed.

Example

Prompt
Use a switch with day set to 8 and cases 1-7 for weekday names. Add a default case that prints "Not a weekday".
Output: Go program and captured output

Case Type Must Match

Every case value needs to be of the same type as the switch expression. Mix in a different type and the program will not compile. In this example, a is an int, so the string case "b" causes an error.

Example

Prompt
Show a switch on an int variable where one case uses a string value, causing a compile error.
Output: Go program and captured output