With the help of switch case we can implement the functionality of as many if statements. In Golang, switch cases can work with strings, list of variables including integer values as well as floating values.
Syntax:
switch optstatement; optexpression{
case expression1: Statement..
case expression2: Statement..
…
default: Statement..
}
Example 1: In this example we can see that by using switch cases and assuming variable as a string type we can make use of switch cases.
// Golang program that uses string switch package main // Here "fmt" is formatted IO which // is same as C’s printf and scanf. import "fmt" // Main function func main() { day := "Tue" // Use switch on the day variable. switch { case day == "Mon": fmt.Println("Monday") case day == "Tue": fmt.Println("Tuesday") case day == "Wed": fmt.Println("Wednesday") } } |
Output :
Tuesday
Example 2:
// Golang program that uses string switch package main // Here "fmt" is formatted IO which // is same as C’s printf and scanf. import "fmt" // Main function func main() { gfg := "Geek" // Use switch on the day variable. switch { case gfg == "Geek": fmt.Println("Geek") case gfg == "For": fmt.Println("For") case gfg == "Geeks": fmt.Println("Geeks") } } |
Output:
Geek
Recommended Posts:
- Golang program that uses switch, multiple value cases
- Golang program that uses fallthrough keyword
- Golang program that uses structs as map keys
- Golang program that uses func with variable argument list
- Golang program that uses func with two arguments
- Golang program that uses defer keyword
- Golang Program that Uses Named Return Values and Defaults
- Golang Program that Uses Multiple Return Values
- Golang Program that uses func as Local Variable
- Golang Program that switch on floating-point numbers
- Golang Program to Show the Duplicate Case Error in Switch Statement
- Switch Case with Break in For Loop in Golang
- Header files in C/C++ and its uses
- How to use a switch case 'or' in PHP?
- Switch Statement in Go
- How to optimize the switch statement in JavaScript ?
- Switch case in R
- What is ISL(Inter-Switch Link)?
- What is SMPS(Switch Mode Power Supply)?
- Decision Making in R Programming - if, if-else, if-else-if ladder, nested if-else, and switch
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

