The switch statement lets you check multiple cases. You can see this as an alternative to a list of if-statements that looks like spaghetti. A switch statement provides a clean and readable way to evaluate cases.

While the switch statement is not unique to Go, in this article you will learn about the switch statement forms in golang.

Related course: Introducing Go: Build Reliable, Scalable Programs

Syntax

The basic syntax of a switch statement is:

1
2
3
4
5
6
7
8
switch var1 {
case val1:
...
case val2:
...
default:
...
}

You can also check conditions:

1
2
3
4
5
6
7
8
switch {
case condition1:
...
case condition2:
...
default:
...
}

The second form of a switch statement is not to provide any determined value (which is actually defaulted to be true).

Instead it test different conditions in each case branch. So what is a condition?

A condition can be x > 10 or x == 8.

The code of the branch is executed when the test result of either branch is true.

The third form of a switch statement is to include an initialization statement:

1
2
3
4
5
6
7
8
9
10
switch initialization {
case val1:
...
case val2:
... default:
...
} switch result: = calculcate (); {
case result < 0: ...
case result > 0: ... default:
// 0}

Variable var1 can be any type, and val1 and val2 can be any value of the same type.

The type is not limited to a constant or integer, but must be the same type; The front braces {must be on the same line as the switch keyword.

You can test multiple potentially eligible values at the same time, using commas to split them, for example: case val1, val2, val3:.

Note Once a branch has been successfully matched, the entire switch code block is exited after the corresponding code is executed, that is, you do not need to use the break statement specifically to indicate an end.

If you want to continue with the code for subsequent branches after you finish the code for each branch, you can use the fallthrough keyword to achieve the purpose.

Example

The example below demonstrates the use of a switch statement in Go.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main
import "fmt"
func main() {
switch a := 1; {
case a == 1:
fmt.Println("The integer was == 1")
fallthrough
case a == 2:
fmt.Println("The integer was == 2")
case a == 3:
fmt.Println("The integer was == 3")
fallthrough
case a == 4:
fmt.Println("The integer was == 4")
case a == 5:
fmt.Println("The integer was == 5")
fallthrough
default:
fmt.Println("default case")
}
}
1
2
The integer was == 1
The integer was == 2

Related course: Introducing Go: Build Reliable, Scalable Programs