Go - Switch Statement
The switch
statement is a shorter way to write a sequence of if-else statements:
- The
switch
cases are evaluated from top to bottom, stopping when a case succeeds - The first
case
expression that equals theswicth
expression will be executed - The
break
statement is not needed at the end of each case like other languages
go
i := getNumber()
switch i {
case 0:
// ...
case 1:
// ...
default:
// Default code to execute if no cases match
}
Simple Statement
The switch
expression may be preceded by a simple statement which executes before the expression is evaluated.
go
switch i := getNumber(); i {
case 0:
// Variables will be only in the scope of the switch statement
default:
// ...
}
Switch Without a Condition
The switch
statement without a condition can be a clean way to write long if-else chains.
go
i := getNumber()
switch {
case i == 0:
// ...
case i == 1:
// ...
default:
// ...
}
// Same as
switch true {
// ...
}