In go, the switch statement allows us to direct program flow in a slightly different way. Instead of multiple if else statements, we can use switch on a single expression. In this article, we will learn how to use Go switch statements.
If we are doing multiple branching logic based on one condition, we can use a switch statement to replace many if else. For example, let's say we are trying to find a ticket price for a customer based on their age.
age := 22
switch {
case age < 21:
fmt.Println("Discount for younger")
case age > 65:
fmt.Println("Discount for older")
default:
fmt.Println("No Discount")
}
We can also use switch statemets based on a value. For example, we can print the month of the year based on an int using the following.
month := 2
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("Month does not exist")
}
You can run the full example code by copying the code below to a file called main.go
and run go run main.go
package main
import "fmt"
// Main function
func main() {
age := 22
switch {
case age < 21:
fmt.Println("Discount for younger")
case age > 65:
fmt.Println("Discount for older")
default:
fmt.Println("No Discount")
}
month := 2
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("Month does not exist")
}
}