...

/

The switch-case Construct

The switch-case Construct

This lesson discusses the switch-case construct in detail.

Introduction

In the last two lessons, we studied the if-else construct. There is another control structure known as the switch-case structure.

The keyword switch is used instead of long if statements that compare a variable to different values. The switch statement is a multiway branch statement that provides an easy way to transfer flow of execution to different parts of code based on the value. The following figure explains the basic structure of the switch-case construct.

switch statement with values

Compared to the C and Java languages, switch in Go is considerably more flexible. It takes the general form:

switch var1 {
case val1:
...
case val2:
...
default:
...
}

Where var1 is a variable which can be of any type, and val1, val2, … are possible values of var1. These don’t need to be constants or integers, but they must have the same type, or expressions evaluating to that type. The opening { has to be on the same line as the switch. The ellipses ... here means that after the case statement, multiple statements can follow without being surrounded by { }, but braces are allowed.

When there is only 1 statement: it can be placed on the same line as case ... :. The last statement, in any case, can also be a return with or without an expression. When the case statements end with a return statement, there also has to be a return statement after the } of the ...