Switch statement
Use the switch statement to select one of the multiple code blocks to be executed.
The switch statement in Go is similar to the switch statement in C, C++, Java, JavaScript, and PHP. The difference is that it only executes matching cases, so there is no need to use break statements.
Switch syntax for single case
switch expression { case x: // Code blockcase y: // Code blockcase z: // ... default: // Code block}
It works as follows:
- The expression is evaluated once.
- The value of the switch expression is compared with the value of each case.
- If it matches, the relevant code block is executed.
- The default keyword is optional. It specifies some code to run if there is no matching case.
Switch example for single case
The following example uses the number of the week to calculate the name of the week:
package main import ( "fmt" ) func main() { day := 4 switch day { case 1: ("Monday") case 2: ("Tuesday") case 3: ("Wednesday") case 4: ("Thursday") case 5: ("Friday") case 6: ("Saturday") case 7: ("Sunday") } }
result:
Thursday
default keyword
The default keyword specifies some code to run when there is no matching case:
package main import ( "fmt" ) func main() { day := 8 switch day { case 1: ("Monday") case 2: ("Tuesday") case 3: ("Wednesday") case 4: ("Thursday") case 5: ("Friday") case 6: ("Saturday") case 7: ("Sunday") default: ("Not a working day") } }
result:
Not a working day
All case values should have the same type as the switch expression. Otherwise, the compiler will throw an error.
package main import ( "fmt" ) func main() { a := 3 switch a { case 1: ("a is one") case "b": ("a is b") } }
result:
./:11:2: Unable to use "b" of type untyped string as int type
Switch statement with multiple values
In a switch statement, each case can have multiple values:
grammar
switch expression { case x, y: // Code block (if the value of the expression is x or y)case v, w: // Code block (if the value of the expression is v or w)case z: // ... default: // Code block (if the expression is not found in any case)}
Example of switch for multiple values
The following example returns different text using the number of the day of the week:
package main import ( "fmt" ) func main() { day := 5 switch day { case 1, 3, 5: ("Odd working days") case 2, 4: ("Even working days") case 6, 7: ("weekend") default: ("Invalid date number") } }
result:
Odd working days
This is the end of this article about the detailed explanation of the usage of switch statements in go. For more related switch content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!