×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang program to demonstrate the switch case with expression

Here, we are going to demonstrate the switch case with expression in Golang (Go Language)?
Submitted by Nidhi, on February 20, 2021 [Last updated : March 02, 2023]

Switch case with expression in Golang

Problem Solution:

In this program, we will use a variable as a switch case expression to select the correct case for execution.

Program/Source Code:

The source code to demonstrate the switch case with expression is given below. The given program is compiled and executed successfully.

Golang code to demonstrate the example of switch case with expression

// Golang program to demonstrate the switch case with expression.

package main
import "fmt"

func main() {
    var month int=6
    
     switch month{ 
       case 1: 
            fmt.Println("JAN") 
       case 2: 
            fmt.Println("FEB") 
       case 3: 
            fmt.Println("MAR") 
       case 4: 
            fmt.Println("APR") 
       case 5: 
            fmt.Println("MAY") 
       case 6: 
            fmt.Println("JUN") 
       case 7: 
            fmt.Println("JUL")
       case 8: 
            fmt.Println("AUG") 
       case 9: 
            fmt.Println("SEP") 
       case 10: 
            fmt.Println("OCT")
       case 11: 
            fmt.Println("NOV") 
       case 12: 
            fmt.Println("DEC") 
       default:  
            fmt.Println("Invalid Month") 
   }  
}

Output:

JUN

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.

In the main() function, we created a variable month, which is initialized with 6, and then we used the variable month as an expression in switch case.

Golang Switch Statement Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.