Go switch
In Go, the switch
statement is used to evaluate a variable or expression and choose a code block to execute based on its value. The syntax of the switch
statement is as follows:
switch expression { case value1: // code to be executed if expression equals value1 case value2: // code to be executed if expression equals value2 ... default: // code to be executed if expression doesn't equal any of the above values }
The expression
in the switch
statement can be a variable or an expression that evaluates to a value. Each case
block specifies a value to be compared against the expression
. If the expression
is equal to a case
value, the code block following that case
statement is executed. If none of the case
values match the expression
, the default
block is executed (if it's present).
Here's an example of using the switch
statement in Go:
dayOfWeek := "Monday" switch dayOfWeek { case "Monday": fmt.Println("Today is Monday.") case "Tuesday": fmt.Println("Today is Tuesday.") case "Wednesday": fmt.Println("Today is Wednesday.") case "Thursday": fmt.Println("Today is Thursday.") case "Friday": fmt.Println("Today is Friday.") case "Saturday": fmt.Println("Today is Saturday.") case "Sunday": fmt.Println("Today is Sunday.") default: fmt.Println("Invalid day of the week.") }
In this example, the program checks the value of the variable dayOfWeek
and executes the appropriate code block based on its value. If dayOfWeek
is equal to "Monday", the message "Today is Monday." is printed. If dayOfWeek
is equal to "Tuesday", the message "Today is Tuesday." is printed, and so on. If dayOfWeek
doesn't match any of the case
values, the message "Invalid day of the week." is printed.
It's worth noting that each case
block in a switch
statement automatically breaks at the end of its code block. If you want to fall through to the next case
block, you can use the fallthrough
keyword. For example:
x := 2 switch x { case 1: fmt.Println("x is 1") fallthrough case 2: fmt.Println("x is 2") fallthrough case 3: fmt.Println("x is 3") default: fmt.Println("x is not 1, 2, or 3") }
In this example, the program checks the value of the variable x
and executes the code block for each case
value that matches x
, including the next one due to fallthrough
. If x
is equal to 2, the message "x is 2" is printed, and then the program falls through to the next case
block, which prints "x is 3".