Home »
Golang
Golang switch statement
By IncludeHelp Last updated : October 05, 2024
Go switch statement
It is a conditional statement in which we have multiway branches i.e. there are multiple options for the given cases. The switch is a way to execute multiple code blocks based on the value passed in the case expression. In Golang, there are two types of switch statements:
- Expression switch
- Type switch
Flow chart
1. Expression switch statement
Expression switch is similar to traditional expressions in a programming language like C, C++, Java. There are multiple blocks of code out of anyone that can be executed based on the given condition.
Syntax
switch optionalStatement; optionalExpression {
case expression1:
// code
case expression2:
// code
...
...
...
default:
// code
}
Important Details
- The entry expression is optional in switch, the default value is True (if nothing is mentioned).
- There is no break statement in Golang's switch statement, the code breaks by default after each case.
- The programmer can explicitly use the break and fall through statements for cases if required.
- Multiple cases of the same case are separated using comma (,).
- The default statement is also optional in case of switch.
Example
Golang program to illustrate the working of switch statement
package main
import "fmt"
func main() {
switch month := 7; month {
case 1:
fmt.Println("Number of days : 31 ")
case 2:
fmt.Println("Number of days : 28")
case 3:
fmt.Println("Number of days : 31")
case 4:
fmt.Println("Number of days : 30")
case 5:
fmt.Println("Number of days : 31")
case 6:
fmt.Println("Number of days : 30")
case 7:
fmt.Println("Number of days : 31")
case 8:
fmt.Println("Number of days : 31")
case 9:
fmt.Println("Number of days : 30")
case 10:
fmt.Println("Number of days : 31")
case 11:
fmt.Println("Number of days : 30")
case 12:
fmt.Println("Number of days : 31")
default:
fmt.Println("No month Exists")
}
}
Output:
Number of days : 31
This is a basic program that shows how a basic expression switch works.
2. Type switch statement
The second type of switch statement is type switch which compares types of value. The switch cases here contain type values for comparing with the interface values passed as a condition to the program.
Syntax
switch optionalStatement; TypeConditionExpression {
case type1:
// code
case type2:
// code
...
...
...
default:
// code
}
Example
Golang program to illustrate the working of type switch
package main
import "fmt"
func main() {
var data interface{} = 4
switch q := data.(type) {
case bool:
fmt.Println("It's a Boolean value")
case int:
fmt.Println("It's an integer value")
case string:
fmt.Println("It's an string value")
default:
fmt.Printf("The type is : %T", q)
}
}
Output:
It's an integer value
This is a basic code showing the working of the type switch statement in Golang. In the further coming articles, we will see different variations of the statement with implementation.