The Golang switch statement starts with the switch keyword followed by the expression and then cases. While working with many conditions, it is tedious to work with the Else If statement. In such cases, we can use this switch statement and write as many cases as you want.
In the Golang switch statement, each case expression compares with the expression, and if it is True, the case block will print. If all the case_expressions fail, the default code block prints. The syntax of it is
switch switch_expression { case case_expression1: statement 1 case case_expression2: statement 2 …… case case_expressionN: statement N default: default statement }
Similar to the else if statement, the GC compiler will check the cases from top to bottom. If any of the case expression results are true, it will execute that block and never go beyond that.
Golang Switch Case Example
This program allows the user to enter any positive number from 0 to 6, where 0 means Sunday and six means Saturday. Next, we used the cases to print the output based on the value.
package main import "fmt" func main() { fmt.Print("Please enter value from 0 to 6 = ") var num int fmt.Scanf("%d", &num) fmt.Println(num) switch num { case 0: fmt.Println("Sunday") case 1: fmt.Println("Monday") case 2: fmt.Println("Tuesday") case 3: fmt.Println("Wednesday") case 4: fmt.Println("Thursday") case 5: fmt.Println("Friday") case 6: fmt.Println("Saturday") default: fmt.Println("Please enter valid Number") } }
The Golang switch case doesn’t need an operand or value to compare with case expressions. Because within the cases, We can write a language expression. It is called a tagless case in Go programming.
package main import "fmt" func main() { fmt.Print("Please enter any Number = ") var num int fmt.Scanf("%d", &num) fmt.Println(num) switch { case num > 0: fmt.Println("Positive Number") case num < 0: fmt.Println("Negative Number") case num == 0: fmt.Println("Zero") default: fmt.Println("Enter a Valid Number") } }