Golang Switch Case

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 Go switch statement and write as many cases as you want.

In the Go switch statement, each case expression compares with the switch expression, and if it is True, the case block will print. If all the case_expressions fails, the default code block prints. The syntax of the Golang Switch Case 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 true, it will execute that block and never go beyond that.

Golang Switch Case Example

In this Golang Switch Case program, we allow the user to enter any positive number from 0 to 6, where 0 means Sunday and six means Saturday. Next, we used switch 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")
    }
}
Golang Switch Case 1

The golang switch case doesn’t need an operand or value to compare with case expressions. Because within the Go cases, We can write an expression. It is called a tagless switch 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")
    }
}
Go Switch Case 2