Back to: Golang
The switch-case statement is used to evaluate a variable or an expression against a list of possible values and execute the corresponding code block. Here’s an example of the switch-case statement in Go along with its output:
package main
import "fmt"
func main() {
day := "Saturday"
switch day {
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")
default:
fmt.Println("Today is Sunday")
}
}
Output:
Today is Saturday
In the example above, the switch statement is used to check the value of the day
variable against a list of possible values. If the value of day
matches one of the cases, the corresponding code block is executed. If none of the cases match, the default block of code is executed.
It’s important to note that in a switch-case statement, only one case will be executed. Once a case is matched, the remaining cases will not be checked. If you want to execute multiple cases, you can use the fallthrough
keyword.